#!/bin/sh
# backup dir, mysql, mongo, and so on.
# Auth: xiongchuan ;  Date: 2023-05-10

### global information ###
IP="192.168.0.12"
BackupDir="/backup/${IP}"
NowDate=$(date +%Y%m%d)
WeekDay=$(date +%u)
BackWeekDay=6
KeepDayBackups=7
KeepWeekBackups=3
RemoveDayDate=$(date -d "-${KeepDayBackups} days" +%Y%m%d)
RemoveWeekDate=$(date -d "-$(expr ${KeepWeekBackups} \* 7) days" +%Y%m%d)

### dir list information ###
DataDir="/data/www    /aaa/bbb   /etc/nginx"
RsyncExcludeDir="logs"
RsyncUser="www"

### mysql information ###
MysqlHost=${IP}
MysqlPort=3306
MysqlUser="root"
MysqlPasswd="xxxxxxxx"
MysqlBackFile="${BackupDir}/mysql_${NowDate}.sql"
MysqlRmFile="${BackupDir}/mysql_${RemoveWeekDate}.sql"

### mongo information ###
MongoHost=${IP}
MongoPort=27017
MongoUser="root"
MongoAuthDb="admin"
MongoPasswd="xxxxxx"
MongoBackDir="${BackupDir}/mongodb_${NowDate}"
MongoRmDir="${BackupDir}/mongodb_${RemoveWeekDate}"

### check free disk ###
CheckFreeDisk() {
   FreeDisk=$(df -BG ${BackupDir} | grep /dev | awk '{print $4}' |awk -F 'G' '{print $1}')
   if [ ${FreeDisk} -lt 10 ];then
      echo "Free disk less then 10G ,exit"
      exit
   fi
}

## rsync dir
RsyncDir() {
  for dir in ${DataDir}; do
     echo "start rsync dir ${IP}:${dir}"
     DirName=$(echo ${dir} | sed 's#^/##g'| sed 's/\//_/g')
     [ -d ${BackupDir}/${DirName} ] || mkdir ${BackupDir}/${DirName} -p
     rsync -auzv --delete --exclude ${RsyncExcludeDir} ${RsyncUser}@${IP}:${dir}/*  ${BackupDir}/${DirName}/
  done
}

## backup dir
BackDir() {
  for dir in ${DataDir}; do
     echo "start backup dir ${IP}:${dir}"
     DirName=$(echo ${dir} | sed 's#^/##g'| sed 's/\//_/g')
     cp -rfp ${BackupDir}/${DirName} ${BackupDir}/${DirName}_${NowDate}
  done
}

## remove old dir
RmDir() {
  for dir in ${DataDir}; do
     echo "start remove old dir ${IP}:${dir}"
     DirName=$(echo ${dir} | sed 's#^/##g'| sed 's/\//_/g')
     rm -rf ${BackupDir}/${DirName}_${RemoveWeekDate}
  done
}

## backup mysql
BackupMysql() {
    mysqldump -u ${MysqlUser} -h ${MysqlHost} -P ${MysqlPort} -p${MysqlPasswd} --all-databases >  ${MysqlBackFile} &&  echo "backup mysql success" || echo "backup mysql failed"
}

## remove old mysql backup
RmMysql() {
   rm -rf ${MysqlRmFile} 
}

## backup mongodb
BackupMongo() {
    mongodump --authenticationDatabase  ${MongoAuthDb} --gzip --host ${MongoHost} --port ${MongoPort} -u ${MongoUser} -p ${MongoPasswd} -o ${MongoBackDir}
}

## remove old mongo backup
RmMongo() {
   rm -rf ${MongoRmDir}
}

## global backup script  
if [ ${WeekDay} -eq ${BackWeekDay} ];then
   CheckFreeDisk
   RsyncDir
   RmDir
   BackDir
   RmMysql
   BackupMysql
   RmMongo
   BackupMongo
else
   CheckFreeDisk
   RsyncDir
fi 
