#!/bin/bash

MYSQL_HOST=""
MYSQL_PORT="30001"
MYSQL_USER="root"
MYSQL_PASSWORD="1qaz2WSX"
BACKUP_BASE=/opt
SAVE_DAYS=15


MYSQL_BACKUP_PATH="${BACKUP_BASE}/mysql"

if [ ! -d ${MYSQL_BACKUP_PATH} ];then
    mkdir -p ${MYSQL_BACKUP_PATH}
fi


DATABASES=$(echo "show databases"| /usr/bin/mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -h ${MYSQL_HOST} -P ${MYSQL_PORT} 2> /dev/null |egrep -v '(Database|schema|mysql|sys)')

if [ $? != 0 ];then
    echo "$(date '+%Y-%m-%d %H:%M:%S') mysql server can't connect." >> /tmp/edoc2_backup.log
    exit 1
fi


#backup mysql 
/usr/bin/mysqldump --master-data=2 -R --add-drop-database --flush-logs --user=${MYSQL_USER} --password=${MYSQL_PASSWORD} --host=${MYSQL_HOST} --port=${MYSQL_PORT} --databases ${DATABASES}  2> /dev/null > ${MYSQL_BACKUP_PATH}/edoc2_$(date +%Y-%m-%d-%H-%M).sql
if [ "$?" == 0 ];then
    echo "$(date '+%Y-%m-%d %H:%M:%S') mysql backup success." >> /tmp/edoc2_backup.log
else
    echo "$(date '+%Y-%m-%d %H:%M:%S') mysql backup faile." >> /tmp/edoc2_backup.log
fi


#delete backufile some time ago
find ${MYSQL_BACKUP_PATH} -name "*.sql" -mtime +${SAVE_DAYS} -exec rm -rf {} \;

