#! /bin/bash

#sleep $[$RANDOM % 30]m

logger="/var/log/backup.log"
borg_bin="/usr/bin/borg"
backup_name=`date +%Y-%m-%d`-test
backup_dest="backup@backup.chapril.org:/srv/backups/`hostname --fqdn`"

export BORG_RSH="ssh -p 2242 -A"

echo ========================================================================
echo "                              New backup"
echo ========================================================================
date
echo ""

echo "== Executing package selection: "
date
echo ""
dpkg --get-selections > /root/package-selections

echo "== Backup pre-hook"
date
echo ""

for file in /etc/borg/scripts/pre-hooks/*; do
	echo "Executing $file...			"
	$file
done

echo "== Backup launch"
date
echo ""

$borg_bin create --info --stats $backup_dest::$backup_name / \
	--exclude /proc \
	--exclude /dev  \
	--exclude /sys  \
	--exclude /var/lib/libvirt/coon \
	--exclude /var/lib/libvirt/maine \
	--exclude /var/lib/libvirt/images/  \
        --exclude '/srv/backups/*.chapril.org' \
					   2>&1

rc=$?
if [[ $rc != 0 ]]; then
    echo "Error in borg create action. Stopping backup."
else
    echo "== Backup info"
    date
    echo ""

    $borg_bin info $backup_dest::$backup_name 2>&1

    echo "== Backup pruning"
    date
    echo ""

    $borg_bin prune -v --keep-daily=7 --keep-weekly=5 $backup_dest 2>&1

    echo "== Backup post-hook"
    date
    echo ""

    for file in /etc/borg/scripts/post-hooks/*; do
	[[ -f "$file" ]] || continue
	    echo "Executing $file...			"
	    $file
    done

    echo ""
    date
fi
	
echo Returned $rc
echo ========================================================================

exit $rc

