#!/usr/bin/bash
#
# Workaround for https://github.com/msktutil/msktutil/issues/124
#

WORKGROUP="CERN"
DCHOST="cerndc.cern.ch"

samba_msg() {
   echo "Error: Adjust your SAMBA configuration first in /etc/samba/smb.conf"
   echo "       [global] section must contain at least following directives:"
   echo "       security  = ADS"
   echo "       workgroup = $WORKGROUP"
}

[ "$UID" -eq 0 ] || { echo "This script must be run as root."; exit 1; }

/usr/bin/grep -q -P "(AlmaLinux|CentOS Linux|Red Hat Enterprise Linux).*(7.|8.|9.)" /etc/redhat-release 2>/dev/null

[ $? -ne 0 ] && exit 0

/bin/hostname | grep ".cern.ch" -q 2>/dev/null

[ $? -ne 0 ] && exit 0

TDBTOOL="/usr/bin/tdbtool"
NET="/usr/bin/net"
TESTPARM="/usr/bin/testparm"

if [ ! -x $TDBTOOL ] || [ ! -x $NET ]; then
   echo "Error: tdbtool and net SAMBA utilities are not installed."
   echo "       (run : #dnf install tdb-tools samba-common-tools)"
   exit 1
fi

$TESTPARM -l -s --parameter-name workgroup 2>/dev/null | /usr/bin/grep -q -P "^$WORKGROUP"

[ $? -ne 0 ] && samba_msg && exit 1

$TESTPARM -l -s --parameter-name security 2>/dev/null | /usr/bin/grep -q -P "^ADS$"

[ $? -ne 0 ] && samba_msg && exit 1

$NET rpc getsid -S $DCHOST

[ $? -ne 0 ] && echo "error running $NET" && exit 1

$TDBTOOL /var/lib/samba/private/secrets.tdb store SECRETS/MACHINE_LAST_CHANGE_TIME/$WORKGROUP 0000 2>/dev/null 1>/dev/null

[ $? -ne 0 ] && echo "error running $TDBTOOL (1)" && exit 1

$TDBTOOL /var/lib/samba/private/secrets.tdb store SECRETS/MACHINE_PASSWORD.PREV/$WORKGROUP none 2>/dev/null 1>/dev/null

[ $? -ne 0 ] && echo "error running $TDBTOOL (2)" && exit 1

$TDBTOOL /var/lib/samba/private/secrets.tdb store SECRETS/MACHINE_PASSWORD/$WORKGROUP none 2>/dev/null 1>/dev/null

[ $? -ne 0 ] && echo "error running $TDBTOOL (3)" && exit 1

exit 0
