#!/bin/bash -e

if [ -z $3 ]; then
    echo "usage: $@ LOG WHERE SERVER"
    exit 1
fi

LOG=$1
WHERE=$2
SERVER=$3

if [ "$4" = "cron" ]; then
    BAREOS_MODE=false
else
    BAREOS_MODE=true
fi

if [ ! -d "$WHERE" ]; then
    mkdir -p "$WHERE"
fi

> $LOG
systemctl stop samba-ad-dc 2>&1 | tee $LOG
rsync -av --delete /var/lib/samba/ ${WHERE}/samba 2>&1 | tee $LOG
systemctl start samba-ad-dc 2>&1 | tee $LOG

sysvol_ntacl=${WHERE}/sysvol_ntacl.tar.gz
if [ -e "$sysvol_ntacl" ]; then
    rm -rf "${sysvol_ntacl}"
fi

echo "Sauvegarde des NTACL de sysvol" | tee $LOG

python3 -c """
from optparse import OptionParser
from samba.samdb import SamDB
from samba.dcerpc import security
from samba.auth import system_session
from samba import getopt
from samba.ntacls import backup_offline
parse = OptionParser()
lp = getopt.SambaOptions(parse).get_loadparm()
creds = getopt.CredentialsOptions(parse).get_credentials(lp)
samdb = SamDB(session_info=system_session(), credentials=creds, lp=lp)
domain_sid = security.dom_sid(samdb.get_domain_sid())
backup_offline(lp.get('path', 'sysvol'), '${sysvol_ntacl}', lp.configfile, domain_sid)
"""

exit 0
