#! /bin/sh

# FTP_HOST=
# FTP_USER=
# FTP_PASS=
# FTP_PATH=
# BACKUP_PATH=
# SRC_DIRS=
# LOCAL_LIMIT_INC=
# LOCAL_LIMIT_FULL=
# FTP_LIMIT_INC=
# FTP_LIMIT_FULL=

[ -r /etc/rdup-ftp.conf ] || exit 1

. /etc/rdup-ftp.conf

KIND=$1

[ -n "$2" ] && SRC_DIRS=$2

if [ x$KIND = xgc ]; then
       echo "Garbage collection"
       cd $BACKUP_PATH
       tmpdir=$(mktemp -t -d rdup-ftp_XXXX)
       curlftpfs $FTP_HOST $tmpdir -o user=$FTP_USER:$FTP_PASS
       for f in $SRC_DIRS; do
           n=$(basename $f)
           echo "Local cleaning for $n..."
           INC=$(ls -r $n-INC* | tail -n +$(($LOCAL_LIMIT_INC +1)) )
           FULL=$(ls -r $n-FULL* | tail -n +$(($LOCAL_LIMIT_FULL +1)) )
           [ -n "$INC" ] && rm -f $INC &
           [ -n "$FULL" ] && rm -f $FULL &
           echo "Remote cleaning for $n..."
           INC=$(ls -r $n-INC* | tail -n +$(($FTP_LIMIT_INC +1)) )
           FULL=$(ls -r $n-FULL* | tail -n +$(($FTP_LIMIT_FULL +1)) )
           [ -n "$INC" ] && rm -f $INC &
           [ -n "$FULL" ] && rm -f $FULL &
       done
       fusermount -u $tmpdir
       rmdir $tmpdir
       exit 0
fi

for SRC_DIR in $(echo $SRC_DIRS); do
	NAME=$(basename $SRC_DIR)
	DATE=$(date "+%Y%m%d.%H%M")
	META=$BACKUP_PATH/rdup/$NAME

	mkdir -p $BACKUP_PATH 2>/dev/null
	mkdir -p $META/ 2>/dev/null

	if [ x$KIND = xfull ]; then
		echo "Making a FULL backup of $SRC_DIR"
		rm $META/timestamp $META/filellist 2>/dev/null
		output=$NAME-FULL-$DATE.tar.gz
	elif [ x$KIND = xinc ]; then
		 echo "Making an INCREMENTAL backup of $SRC_DIR"
		 output=$NAME-INC-$DATE.tar.gz
	else
		echo "No action given, exiting."
		exit 2
	fi

	echo "Building tarball..."

	rdup -N $META/timestamp $META/filellist $SRC_DIR | rdup-tr -Otar | gzip -c -f > $BACKUP_PATH/$output

	if [ ! $? -eq 0 ]; then
		echo "Failure when creating tarball $output"
		exit 1
	fi

	echo "Uploading..."

	lftp <<EOF
open $FTP_HOST
user $FTP_USER $FTP_PASS
lcd $BACKUP_PATH
cd $FTP_PATH
put $output
EOF

	if [ ! $? -eq 0 ]; then
		echo "Failure when uploading tarball $output on $FTP_HOST"
		exit 1
	fi

	echo "Backup successfull."
done

