#!/bin/bash

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
    if [ -e "$KEYFILE" ]
    then
        /bin/rm "${KEYFILE}"
    fi
    exit $rc
}
trap samba_backup_clean EXIT
set -e

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

# shellcheck disable=SC1091
. /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"
samba-tool domain exportkeytab "$KEYFILE" --principal="$USER" 2> /dev/null
kinit "$USER" -k -t "$KEYFILE"

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

# do backup
if ! /usr/share/eole/sbin/samba_backup "$REPORT" "$WHERE" "$SERVER" "$1" > /dev/null 2> /dev/null
then
    echo "Sortie de samba_backup en erreur"
    exit 1
fi

# remove keytab
kdestroy
rm -f "$KEYFILE"

if [ "$bareos_mode" = "0" ]; then
    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

