#!/bin/bash

mysqllogbin="/usr/bin/mysqlbinlog"


mysqlLogDir="/var/lib/mysql/"


mysql_user=`/usr/local/mssBak/script/encryption 1 "6266706d736f7a7c7b6b7f7b7f"`
mysql_pw=`/usr/local/mssBak/script/encryption 1 "2b3a392757557b697b7e7e757b777c"`


`/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
flush logs;
_EOF_`

lastLogFileNo=`ls $mysqlLogDir | grep -e '[a-zA-Z]-[01]-bin.'|grep -v 'index' | awk -F. 'BEGIN{max=0;} {if( NR!=1 && $2>max ) max=$2} END{printf "%06d",max-1}'`


logFileNamePrefix=`ls $mysqlLogDir | grep -e '[a-zA-Z]-[01]-bin.'|head -1|awk -F. '{print $1}'`

# There is no log
if [ `echo $lastLogFileNo | grep -c '-'` -eq 1 ] ;then
	exit
fi


nowLogFileName=$logFileNamePrefix.$lastLogFileNo

# bzip the log file
cd $mysqlLogDir
if [ ! -e $mysqlLogDir$nowLogFileName.bk.bz2 ] ;then
	rm -rf $nowLogFileName.bk
	$mysqllogbin $nowLogFileName >> $nowLogFileName.bk
	bzip2 -z $nowLogFileName.bk
fi


# Send log files
if [ ! -f /etc/syslog_server_config ] ; then
  echo "Syslog server not configured. Please run script 'config_syslog_server'"
  exit
fi

ip_addr=`cat /etc/syslog_server_config|grep "ip_addr"|awk -F":" '{print $2}'`
ping_reply=`ping -c 2 $ip_addr|grep "time="`
if [ -z "$ping_reply" ] ; then
  echo "Syslog server $ip_addr is not reachable!"
  exit
fi

user_name=`cat /etc/syslog_server_config|grep "user_name"|awk -F":" '{print $2}'`
password=`cat /etc/syslog_server_config|grep "password"|awk -F":" '{print $2}'`

if [ ! -z "`/etc/sftp_auditlog_files $ip_addr $user_name $password $mysqlLogDir app $nowLogFileName.bk.bz2 |grep "100%"`" ] ; then
	rm -f $mysqlLogDir$nowLogFileName.bk.bz2
fi


