#!/usr/bin/bash

#Tate:2022.5.6
#Author:Yingjian
#function: 定时备份redis aof 文件
#env

workdir=`cd $(dirname $0);pwd`
same_day=`date +%F`
seven_day_age=`date -d '-7 day' "+%F"`
data_dir=/usr/local/redis/data
backup_dir=/data/backup/redis
logfile=$workdir/backup_reids.log
redis=/usr/local/redis/bin/redis-cli

echo "----`date` started sh---------------------------" >> $logfile

if [ -d $backup_dir ];then
	echo "`date` $backup_dir 备份目录已存在" >> $logfile
else
	echo "`date` $backup_dir 备份目录不存在 正在创建 " >> $logfile
	mkdir -p $backup_dir
fi

#判断redis服务器是否正在创建rdb文件

while :
do
sleep 1
number=`$redis info Persistence |grep rdb_bgsave_in_progress |awk -F":" '{print $NF}'`
if [ `echo ${number} | awk -v tem=0 '{print($1>tem)? "1":"0"}'` -eq "0" ];then
echo "rdb_bgsave_in_progress为 0 正在退出循环 执行备份中" >> $logfile
break
fi

done

if [ -d $backup_dir/${same_day} ];then
	echo "`date` $backup_dir/${same_day} 备份目录已存在" >> $logfile
else
	echo "`date` $backup_dir/${same_day} 备份目录不存在 正在创建" >> $logfile
	mkdir -p $backup_dir/${same_day}
fi
echo "`date` cp aoffile start " >> $logfile
#备份redis aof文件
cp -arf $data_dir/appendonly.aof $backup_dir/${same_day}
#备份redis rdb文件
#手动执行bgsave
echo "`date` start bgsave " >> $logfile
$redis bgsave >> $logfile
sleep 30
echo "`date` end bgsave" >> $logfile

cp -arf $data_dir/dump.rdb $backup_dir/${same_day}

echo "`date` backup complete" >> $logfile

#删除过期目录
rm -rf $backup_dir/${seven_day_age}

