#/bin/bash
set -x
#-------------------------------------------------------------
database=CMDB
user=root
password=root
#-------------------------------------------------------------
time=$(date +%Y%m%d%H%M%S)
folder=$(ls /opt | grep -w mysqldatabase_bak)
#-------------------------------------------------------------
#database exprot
if [ $folder == mysqldatabase_bak ] ; then
  mysqldump -u$user -p$password $database > /opt/mysqldatabase_bak/$database$time.sql
  zip -r /opt/mysqldatabase_bak/$database$time.sql.zip /opt/mysqldatabase_bak/$database$time.sql
  rm -f /opt/mysqldatabase_bak/$database$time.sql
else
  mkdir /opt/mysqldatabase_bak
  mysqldump -u$user -p$password $database > /opt/mysqldatabase_bak/$database$time.sql
  zip -r /opt/mysqldatabase_bak/$database$time.sql.zip /opt/mysqldatabase_bak/$database$time.sql
  rm -f /opt/mysqldatabase_bak/$database$time.sql
fi
#-------------------------------------------------------------
#database Periodically delete
find /opt/mysqldatabase_bak -mtime +7 -name "*.zip" -exec rm -rf {} \;
#-------------------------------------------------------------
#crontab
crontab=$(cat /var/spool/cron/root | grep mysqldatabase_bak_for_centos.sh | awk '{print $8}')
if [ $crontab == ./mysqldatabase_bak_for_centos.sh  ] ; then
  echo "crontab is ok!"
else
  echo "1 1 * * * cd /opt/mysqldatabase_bak;bash ./mysqldatabase_bak_for_centos.sh" >> /var/spool/cron/root
fi
#-------------------------------------------------------------
#move
pwd=$(pwd)
if [ $pwd == /opt/mysqldatabase_bak  ] ; then
  echo "The scripts directory is ok!"
  echo "The scripts directory is /opt/mysqldatabase_bak"
else
  cp  mysqldatabase_bak_for_centos.sh /opt/mysqldatabase_bak
  rm -f mysqldatabase_bak_for_centos.sh
fi