#!/bin/bash

echo $@

function samba_backup_clean
{
    rc="$?"
    # protection avant rm
    if [ -n "${WHERE}" ]
    then
        # j'affiche ce que je supprime, car il ne devrait rien avoir !
        /bin/rm -rvf "${WHERE%/}"/tmp*
    fi
    keyfile="$container_path_domaine$KEYFILE"
    if [ -e "$keyfile" ]
    then
        /bin/rm "${keyfile}"
    fi
    exit $rc
}
trap samba_backup_clean EXIT
set -e

container_path_domaine=$(CreoleGet container_path_domaine)

# shellcheck disable=SC1091
. $container_path_domaine/etc/eole/samba4-vars.conf

# shellcheck disable=SC1091
. $container_path_domaine/etc/samba/samba_backup.conf
WHEN=$(date "${WHEN_FORMAT}")

if [ -n "$1" ] && [ "$1" = "cron" ]; then
        bareos_mode=0
        REPORT="${WHERE%/}/samba_backup_${WHEN}.report"
else
        bareos_mode=1
        REPORT="${WHERE%/}/samba_backup.report"
fi

# create backup folder if necessary
if [ ! -e "${WHERE}" ]; then
    mkdir -p "${WHERE}"
fi

# get keytab to backup server without password
USER="$AD_ADMIN@${AD_REALM^^}"
KEYFILE="/tmp/backup.keytab"
CreoleRun "samba-tool domain exportkeytab "$KEYFILE" --principal="$USER"" domaine
CreoleRun "kinit \"$USER\" -k -t \"$KEYFILE\"" domaine

if CreoleRun "lsof /home/sysvol >/dev/null 2>&1" domaine
then
    echo "Des sessions ouvertes, redémarrage de Samba"
    # shellcheck disable=SC1091
    CreoleRun ". /etc/eole/samba4-vars.conf; . /usr/lib/eole/samba4.sh stop_samba; start_samba" domaine
fi

# do backup
#if [ ! $? = 0 ]
if ! CreoleRun "/usr/share/eole/sbin/samba_backup \"$REPORT\" \"$WHERE\" \"$SERVER\" \"$1\"" domaine > /tmp/sauvegarde
then
    cat /tmp/sauvegarde
    echo "Sortie de samba_backup en erreur"
    exit 1
fi
CreoleRun "net getlocalsid | awk -F': ' '{print \$2}'" domaine > "$WHERE/samba.sid"
echo "Sauvegarde réussie"

# remove keytab
CreoleRun kdestroy domaine || true
CreoleRun "rm -f \"$KEYFILE\"" domaine || true

if [ "$bareos_mode" = "0" ]; then
    echo "Recherche des anciennes archives"
    nb_archive=$(find "$WHERE" -type f -name "samba-backup*bz2" -mtime +"$DAYS" -delete -printf '.' | wc -c)
    echo "Removed ${nb_archive} archives older than $DAYS days." >> "$REPORT"
fi

exit 0
