#!/bin/bash

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

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

retrie_on_fail(){
    if [ $1 -ne 0 ]; then
        keep=$(($BK_KEEP_FULL-1))
        if [ $keep -gt 0 ]; then
            run_duplicity remove-all-inc-of-but-n-full $keep --force
        else
            cat <<EOF | lftp $host
            user $user $ftppass
            glob rm $remotedir/*-inc*
            glob rm $remotedir/*-new-signatures*
EOF
        fi
        backup "cleaned"
        leave $?
    fi
}

backup(){
    retries=$1
    shift

    cleanup
    echo "Removing old backups"
    delete_old_backups

    echo "Running pre_actions"
    pre_actions
    exit_on_fail $? "Pre_action failed"
    echo "Creating encrypted incremental backup: $bckplist "
    export PASSPHRASE="$encpass"
    export FTP_PASSWORD="$ftppass"
    set -x
    /usr/bin/duplicity --verbosity $verbosity \
        --full-if-older-than $BK_FULL_FREQ \
        --include ${bckplist// / --include } \
        --exclude /root/.cache/duplicity/ \
        --exclude '**' \
        / \
        $remote
    ret=$?
    set +x
    unset PASSPHRASE
    unset FTP_PASSWORD
    if [ -z "$retries" ]
    then
        retrie_on_fail $ret "Duplicity failed"
    else
        exit_on_fail $ret "Duplicity failed"
    fi

    echo "Backup completed"

    collection_state
    echo "All Done"
}
backup
ret=$?
retrie_on_fail $ret
leave $ret
