#!/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

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

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

python3 -c """
from optparse import OptionParser
from samba.samdb import SamDB
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)
backup_offline(lp.get('path', 'sysvol'), '${sysvol_ntacl}', samdb, lp.configfile)
"""

exit 0
