#!/bin/bash
# mydumper 备份脚本
# sh mydumper.sh -u user -p passwd -o /backdir [ -d 4(保存天数) -b databases -t table -h locahost —P port -s SockFile -c]
# 参数说明：
# -u : (必选)备份使用用户
# -p : (必选)用户密码
# -o : (必选)备份路径
# -d : [可选]备份保存天数
# -b : [可选]要备份哪个库(选择后只备份这个库)
# -t : [可选]要备份哪个表(选择后只备份这个表，必须配合 -b 使用)
# -h : [可选]备份 MySQL 地址，默认 localhost
# -P : [可选]备份 MySQL 端口，默认 3306
# -s : [可选]使用socket连接
# -x : [可选]备份线程，默认4线程
# -c : [可选]是否需要压缩备份

PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin

check_mydumper=$(yum list installed|grep mydumper |wc -l)
mydumper_rpm='https://github.com/maxbube/mydumper/releases/download/v0.9.5/mydumper-0.9.5-2.el7.x86_64.rpm'

mount_dir=''

if [ ${check_mydumper} != 0 ];then
  mydumper_version=$(mydumper --version  |awk -F, '{print $1}')
  echo "mydumper already installed.The version is ${mydumper_version}"
else
  echo "mydumper has not been installed, install now..."
  yum install ${mydumper_rpm} || echo -e "\n########Install failed.Please check.########\n" && exit 1
fi

cmd="mydumper -R -e "

log_dir=/tmp/mydumper.log
while getopts :u::p::o:d:b:t:h:x:s:P:c opt;do
  case $opt in
    c) cmd=$cmd" -c ";;
    u) cmd=$cmd" -u $OPTARG"
       user=$OPTARG ;;
    p) cmd=$cmd" -p $OPTARG"
       passwd=$OPTARG ;;
    o) cmd=$cmd" -o $OPTARG/`date -d yesterday +%Y%m%d`" 
       back_dir=$OPTARG ;;
    h) cmd=$cmd" -h $OPTARG" ;;
    P) cmd=$cmd" -P $OPTARG" ;;
    b) cmd=$cmd" -B $OPTARG" ;;
    t) cmd=$cmd" -T $OPTARG" ;;
    x) cmd=$cmd" -t $OPTARG" ;;
    s) cmd=$cmd" -S $OPTARG" ;;
    d) save_days=$OPTARG ;;
    ?) exit 1;;
  esac
done

check_back_dir(){
if [ ! -d $back_dir ];then
  mkdir -p $back_dir
fi
}

# 删除旧备份
del_save_days(){
if [ $? -eq 0 ];then
  #find $back_dir -maxdepth 1 -type d -ctime +$save_days | xargs rm -rf
  rm -rf $back_dir/`date --date "$save_days days ago" +%Y%m%d`
fi
}

# 是否需要拷贝备份到挂载磁盘
mount_backup(){
  rsync -a $back_dir/`date -d yesterday +%Y%m%d` $mount_dir/
  echo "`date` 拷贝备份到挂载目录" 2>&1 >>$log_dir
  rm -rf $mount_dir/`date --date "15 days ago" +%Y%m%d`
  echo `date` ' 删除挂载目录15天前备份' 2>&1 >>$log_dir
}

if [ -z  "$user" -a -z "$passwd" -a -z "$back_dir" ];then
  exit 1
fi

check_back_dir
echo "`date` $cmd" >$log_dir
del_save_days
$cmd
# mount_backup