#!/bin/bash

src=/PATH/TO/SOURCE
base=/PATH/TO/STORAGE
keyfile=/PATH/TO/KEY
excludes="--exclude=USELESS/** --exclude=TOBIG/**"
user=USERNAME
snarbase=$base

backup_count=$(ls ${base}/backup.inc*.tgz.ssl 2>/dev/null | wc -l)
backup_full=${base}/backup.tgz.ssl

backup_inc=${base}/backup.inc$(ls ${base}/backup.inc*.tgz.ssl 2>/dev/null | wc -l).tgz.ssl
backup_snar=${snarbase}/backup.snar
if [ ! -f $backup_full ]; then
    echo "No previous Backup found => starting new level 0 Backup"
    backup=$backup_full
    backup_lvl=0
    if [ -f $backup_snar ]; then
        echo "Snar file ($backup_snar) found without existing level 0 Backup, somethings probably broken."
        echo "Stopping for safety, either find the missing level 0 Backup or delete the snar file."
        exit
    fi
else
    backup=$backup_inc
    backup_lvl=1
    echo "Restoring snar base (backup)"
    cp ${backup_snar}.bak $backup_snar
fi

echo "* backup (level $backup_lvl) to: $backup ($backup_snar)"
tar -cpz \
        --listed-incremental=$backup_snar $excludes --exclude-backups --exclude-caches --exclude-tag-under=.TARIGNORE \
        $src | su $user -c "openssl enc -e -aes256 -pass file:$keyfile -out $backup"

if [ $backup_lvl -eq 0 ]; then
    echo "Creating snar base (backup)"
    cp $backup_snar ${backup_snar}.bak
fi
