#!/bin/sh
bak_dir="./baklog" #save *tar.gz dir
log_dir="./log.bak.tar" #get log.bak dir
bak_fn=`date +%Y%m%d%H%M%S`.tar.gz
########################################
savecnt=4
findname="$bak_dir/*.tar.gz"
declare -A dic;
########################################
#create dir
if [ ! -d "$bak_dir" ]; then
mkdir $bak_dir
fi
#create
for i in $(seq 1 $savecnt);do
dic["$bak_dir/$i.tar.gz"]=$i
done
#save find files
cnt=0
for k in `ls $findname`;do
cnt=$((cnt + 1))
#echo "ls--"$k
if [ -v dic[$k] ] && [ $cnt -lt $savecnt ];then
#echo "Found" $k
dic[$k]=$k
else
#echo "other delete " $k
rm -f $k
fi
done
#find
i=0
for i in $(seq 1 $savecnt);do
#echo "hhh" ${dic["$bak_dir/$i.tar.gz"]}
if [ "${dic["$bak_dir/$i.tar.gz"]}" != "$bak_dir/$i.tar.gz" ];then
break
fi
done
#find next file and delete
deleti=$((i+1))
if [ $deleti -gt $savecnt ];then
deleti=1
fi
if [ -f "$bak_dir/$deleti.tar.gz" ];then
#echo "next delete $bak_dir/$deleti.tar.gz"
rm -f "$bak_dir/$deleti.tar.gz"
fi
#creat new file
#echo "Got Key $i.tar.gz"
############################################
#find files then tar all. bak it to bak_dir
find ./ -name "*.log" -or -name "*.ini" -or -name "*.txt" -or -name "*.sh" | xargs tar -zcf "$bak_dir/$i.tar.gz"
tar -cf $log_dir $bak_dir/*.tar.gz
#cyc tars
#cnt=`ls $bak_dir/*.tar.gz 2>/dev/null | wc -l `
#if [ $cnt -ge 20 ]; then
# rm -f $bak_dir/*.tar.gz
#fi