#!/bin/bash
#
# This script only rotates the binary logs. The normal logs are rotated
# via /etc/logrotate.d/mysql-server.
#
# The number of binary logs that should be kept can be configured in
#	/etc/mysql/debian-log-rotate.conf
#
set -e
set -u

###########################################################################

M="/usr/bin/mysql --defaults-file=/etc/mysql/debian.cnf"
MA="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"
tmp=`tempfile`;

my_exit () {
  rm $tmp
  exit $1	  
}

test -x /usr/bin/mysqladmin || exit 0

# Read config and see if we should rotate at all.
. /etc/mysql/debian-log-rotate.conf
if [ "$KEEP_BINARY_LOGS" -eq 0 ]; then
  my_exit 0
fi

# Test if the server is up and running.
if ! $MA --silent ping >/dev/null; then
  my_exit 0
fi

# Retrieving list of file names. Can fail if no binary logs are in use.
if ! echo 'SHOW MASTER LOGS;' | $M --skip-column-names >$tmp 2>&1; then
  if grep -q 'You are not using binary logging' $tmp; then
    my_exit 0
  else
    echo "Unknown problem retrieving MySQL master log filenames in $0."
    cat $tmp
    my_exit 1
  fi
fi

# Test if we have enough log files to rotate and do so if.
if [ `wc -l < $tmp` -gt $KEEP_BINARY_LOGS ]; then
  filename=`tail -n $KEEP_BINARY_LOGS $tmp | head -n 1`
  echo "PURGE MASTER LOGS TO '$filename';" | $M
fi

my_exit 0
