##########################################################################

# Author:                                                                #

#          gfsunny@163.com                                               #

# Create:                                                                #

#   2014/11/05                                                    #

# Function:                                                              #

#          copy files and compare the similarities and differences       #

# between two directories                                                #

##########################################################################

CurrentDate=`date +%Y%m%d`

BeforeDayDate=`date -d '1 days ago' +%Y%m%d`

SourceDir=/etc

BackupDir=/var/backups

if [ ! -d "$BackupDir" ];then

mkdir "$BackupDir"

if [ $? == 0 ];then

echo "create $BackupDir success" > "$BackupDir"/"$CurrentDate".log

else

echo "create $BackupDir fail"  > "$BackupDir"/"$CurrentDate".log

exit 1

fi

else

        echo "$BackupDir exists" > "$BackupDir"/"$CurrentDate".log

fi

cd $BackupDir

if [ ! -d "$CurrentDate" ];then

        mkdir "$CurrentDate"

        \cp -r $SourceDir/* "$BackupDir"/"$CurrentDate"

if [ $? == 0 ];then

echo "copy $SourceDir success" >> "$BackupDir"/"$CurrentDate".log

else

echo "copy $SourceDir fail"  >> "$BackupDir"/"$CurrentDate".log

exit 2

fi

else

        cd "$CurrentDate"

        rm -fr *

        \cp -r $SourceDir/* "$BackupDir"/"$CurrentDate"

if [ $? == 0 ];then

echo "copy $SourceDir success" >> "$BackupDir"/"$CurrentDate".log

else

echo "copy $SourceDir fail"  >> "$BackupDir"/"$CurrentDate".log

exit 3

fi

fi

cd $BackupDir

if [ ! -d "$BeforeDayDate" ];then

echo "keep $CurrentDate dir" >> "$BackupDir"/"$CurrentDate".log

exit 0

else

Different=`diff -r "$CurrentDate" "$BeforeDayDate" 2>/dev/null |wc -l`

if [ "$Different" -eq 0 ];then

rm -rf "$BeforeDayDate"

echo "$BeforeDayDate has been deleted!" >> "$BackupDir"/"$CurrentDate".log

else

echo "$CurrentDate is diff and keep it" >> "$BackupDir"/"$CurrentDate".log

exit 0

fi

fi