#!/bin/sh

# some config
dirout=/var/ftp/backup
logfile=/var/log/mkbackup.log
# num of days ago to keep files, any oldest which present in FILE will be removed!
# for ex: if keepdays is set to '2', then today and yesterday files will be kept.
keepdays=9

if [ $# -lt 1 ]; then
    echo "Usage: ${0##*/} FILES..."
    echo "    where each FILE contains list of absolute pathed dirs"
    echo "    that should be backed up; it is passed to '-T' tar option"
    exit 0
fi

curdate=`date +%Y%m%d`
curdate_full=`date "+%Y-%m-%d %H:%M:%S"`

echo "############## $curdate_full Starting mkbackup... ##############" | tee -a $logfile
echo "####    dirout:  $dirout"
echo "####    logfile: $logfile"
echo

args=$*

# backup part
while [ -n "$1" ]; do
    #if [ "${dir:0:1}" == "#" ]; then
    #	continue
    #fi

    # make mrproper :)
    lst=$1
    fname=${lst##*/}
    fname=${fname%*.lst}
    fname=${fname//./_}

    # create new tars, then bz2'em
    fname=$dirout/$fname.$curdate.tar
    fnamebz2=$fname.bz2

	# ignore tar exit code 1 'some files differ' not to leave non-compressed
	# file alone. we assume that 0 and 1 code means success here
    tar -csp -T $lst >$fname 2>>$logfile
	if [ $? -eq 0 ] || [ $? -eq 1 ]; then
		bzip2 -9z $fname 2>>$logfile && \
		bzip2 -t $fnamebz2 2>>$logfile
	fi

    if [ $? -eq 0 ]; then
	echo "created: $fnamebz2"
    else
	echo "ERROR: while processing $fnamebz2"
    fi

    shift
done

# cleanup part
for arg in $args; do
    # make mrproper :)
    lst=$arg
    fname=${lst##*/}
    fname=${fname%*.lst}
    fname=${fname//./_}

    # remove old backups
    for f in $(find $dirout -name "$fname.*.tar.bz2" -daystart -mtime +$[$keepdays-1])
    do
	rm "$f"
	if [ $? -eq 0 ]; then
	    echo "removed: $f"
	fi
    done
done
