#!/bin/bash
# author: movekj
# descript: backup mysql. full backup in sunday,incremental backup in other day.(for Innodb Store Engine)
# version: 0.0.1 
### DEFINE VARIABLES
PATH="/usr/java/latest/bin:/usr/lib64/qt-3.3/bin:/usr/java/latest/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"
BackupUser=backuper
BackupPassword=.......1
WorkPath=/home/backup
LogPath=/home/backup/log/
FullBackupPath=/home/backup/full/
IncreBackupPath=/home/backup/incre/
DayOfWeek=`date +%u`
WeekOfYear=`date +%W`
Date=`date +%F`
### DEFINE FUNCTION
CreateBackupPath() {
if [ ! -d $1$2 ]
then
    mkdir -p $1$2 && echo -e "`date` \033[31m$1$2 is create successful!\033[0m"#>> $LogPath$WeekOfYear/backup_$Date.log 
fi
}
DeleteOldBackup() {
BackupNum=`ls $1 | wc -l`
if [ $BackupNum -gt 3 ]
then
    OldBackupNum=$[$BackupNum-3]
    OldBackup=`ls -t $1 | tail -$OldBackupNum`    ### FIND OLD BACKUP
for I in $OldBackup
do
    rm -rf $1$I && echo "`date` $1$I is deleted!"  >> ${LogPath}backup_delete.log
done
fi
}
Delete() {
        DeleteOldBackup $FullBackupPath    ### DELETE OLD FULL BACKUP
        DeleteOldBackup $IncreBackupPath   ### DELETE OLD INCREMENTAL BACKUP
        #DeleteOldBackup $LogPath          ### DELETE OLD LOG FILE 
}
CreateBackupPath $LogPath $WeekOfYear      ### CREATE BACKUP LOG PATH
CreateBackupPath $FullBackupPath $WeekOfYear   ## CREATE FULL BACKUP PATH
CreateBackupPath $IncreBackupPath $WeekOfYear    ### CREATE INCREMENTAL BACKUP PATH
### START PROGRESS
if [ $DayOfWeek -eq 1 ]
then
innobackupex --user=$BackupUser --password=$BackupPassword $FullBackupPath$WeekOfYear 2>> $LogPath$WeekOfYear/Full_backup_$Date.log >> $LogPath$WeekOfYear/Full_backup_$Date.log
        if [ $? -eq 0 ]
        then
            Delete
        fi
elif [ $DayOfWeek -eq 2 ]
then
NewestFullBackup=`ls -t $FullBackupPath$WeekOfYear | head -1`    ### FIND NEWEST FULL BACKUP
innobackupex --user=$BackupUser --password=$BackupPassword --incremental --incremental-basedir=$FullBackupPath$WeekOfYear/$NewestFullBackup $IncreBackupPath$WeekOfYear 2>> $LogPath$WeekOfYear/Incre_backup_$Date.log >> $LogPath$WeekOfYear/Incre_backup_$Date.log
    if [ $? -eq 0 ]
    then 
        Delete
    fi
else
NewestIncreBackup=`ls -t $IncreBackupPath$WeekOfYear | head -1`    ### FIND NEWEST INCREMENTAL BACKUP
innobackupex --user=$BackupUser --password=$BackupPassword --incremental --incremental-basedir=$IncreBackupPath$WeekOfYear/$NewestIncreBackup $IncreBackupPath$WeekOfYear 2>> $LogPath$WeekOfYear/Incre_backup_$Date.log >> $LogPath$WeekOfYear/Incre_backup_$Date.log
        if [ $? -eq 0 ]
        then
            Delete
      fi
fi