#!/bin/bash

DIR=$(realpath $(dirname $0))
if [ ! -z "$1" ]; then
   conf_file=$1
   shift
fi
source $DIR/inc.sh

exit_on_fail(){
        [ $1 -ne 0 ] && leave $@
        echo "Done"
}

retrie_on_fail(){
        cat <<EOF | lftp $host
user $user $ftppass

rm -rf $remotedir
mkdir $remotedir
EOF
backup "cleaned"
leave $?
}

backup(){

        retries=$1
        shift
        export PASSPHRASE="$encpass"
        export FTP_PASSWORD="$ftppass"
        #set -x

        echo "Removing old backups"
        /usr/bin/duplicity remove-older-than $BK_FULL_LIFE \
                --force ftp://$user@$host/$remotedir/
        /usr/bin/duplicity remove-all-inc-of-but-n-full $BK_KEEP_FULL \
                --force ftp://$user@$host/$remotedir/
        /usr/bin/duplicity remove-all-but-n-full $BK_KEEP_FULL \
                --force ftp://$user@$host/$remotedir/

        echo "Running pre_actions"
        pre_actions
        exit_on_fail $? "Pre_action failed"
        echo "Creating encrypted incremental backup: $bckplist "
        /usr/bin/duplicity \
                --full-if-older-than $BK_FULL_FREQ \
                --include ${bckplist// / --include } \
                --exclude '**' \
                / ftp://$user@$host/$remotedir/
        ret=$?
        if [ -z "$retries" ]
        then
                retrie_on_fail $ret "Duplicity failed"
        else
                exit_on_fail $ret "Duplicity failed"
        fi

        echo "Backup completed"

        echo "Cleaning"
        /usr/bin/duplicity cleanup --force --extra-clean ftp://$user@$host/$remotedir/
        echo "Removing backup cache"
        rm -rf /root/.cache/duplicity/
        echo "Backups state"
        /usr/bin/duplicity collection-status ftp://$user@$host/$remotedir/
        #set +x
        unset PASSPHRASE
        unset FTP_PASSWORD
        echo "All Done"
}
backup
leave $?
