#!/bin/bash

# see : https://wiki.samba.org/index.php/Rsync_based_SysVol_replication_workaround

set -e

SAMBA4_VARS=/etc/eole/samba4-vars.conf

if [ -f "${SAMBA4_VARS}" ]
then
    . "${SAMBA4_VARS}"
else
    # Template is disabled => samba is disabled
    exit 0
fi

#rsync
# -A : --acls     preserve ACLs (implies --perms)
# -X : --xattrs   preserve extended attributes
# -a : --archive  archive mode; equals -rlptgoD (no -H,-A,-X)
# -v : --verbose  increase verbosity
# -z : --compress compress file data during the transfer
# --delete-after  receiver deletes after transfer, not during
# --ignore-times          don't skip files that match size and time
# --force                 force deletion of dirs even if not empty
#rsync -XAavz --delete-after --password-file=/var/lib/samba/rsyncd-sysvol.secret rsync://sysvol-replication@192.168.0.5/SysVol/ /var/lib/samba/sysvol

if [ -n "${AD_DC_SYSVOL_REF}" ]
then
    if [ "${AD_DC_SYSVOL_TYPE}" = "windows" ]
    then
        echo "FIXME: a faire"
        # si le distant est windows, alors on utilise le partage sysvol
        # info: https://wiki.samba.org/index.php/Enabling_the_Sysvol_Share_on_a_Windows_DC
        #mkdir -p /media/sysvol
        #kinit -V -5  -k -t "${AD_ADMIN_KEYTAB_FILE}"
        #umount //${AD_DC_SYSVOL_REF}/SYSVOL/
        #mount -t cifs -o user=${AD_ADMIN}@${AD_REALM^^},sec=krb5 //${AD_DC_SYSVOL_REF}/SYSVOL /media/sysvol
        #if [ $? -eq 0 ]
        #then
        #    #rsync --verbose -a /media/sysvol /home/sysvol
        #    umount //${AD_DC_SYSVOL_REF}/sysvol\$/
        #fi
    else
        # Warning: Make sure that the destination folder is really your SysVol folder, because the command
        # will replicate to the given directory and removes everything in it that isn't also on the source!
        # You could damage your system! So check the output carefully to see if the replication is doing what
        # you expect!
        tcpcheck 2 ${AD_DC_SYSVOL_REF}:22 &>/dev/null || { echo "Impossible de joindre le serveur sysvol"; exit 0; }
        rsync --rsh='ssh' \
                   --compress --verbose \
                   --acls --xattrs \
                   --archive --ignore-times \
                   --delete-after --force \
                   --stats root@${AD_DC_SYSVOL_REF}:/home/sysvol/ /home/sysvol/

        #samba-tool ntacl sysvolcheck
        #samba-tool ntacl sysvolreset
    fi
fi
