#!/bin/sh
set -e
[ ! -f /etc/samba/smb.conf ] || grep -q "server role = standalone server" /etc/samba/smb.conf || exit 0
. /usr/share/omix/dclib

systemctl mask --now smbd nmbd winbind
systemctl stop samba-ad-dc
rm -rf /etc/samba/smb.conf /etc/krb5.conf \
    /var/run/samba/* /var/lib/samba/* /var/cache/samba/* /var/lib/samba/private/*

domain=$(hostname -d)
realm=$(echo $domain | tr '[:lower:]' '[:upper:]')
wkg=$( echo $domain | sed 's/^\(.*\)\..*$/\1/') #'
host -t SRV -W 1 _ldap._tcp.$domain > /dev/null 2>&1 && mode=join || mode=provision

if [ "$mode" = provision ]; then
    getpasswd medium
    [ -n "$pass" ] && pass="--adminpass=$pass"
    samba-tool domain provision --server-role=dc --use-rfc2307 \
    --dns-backend=SAMBA_INTERNAL --realm=$realm \
    $pass \
    --domain=$wkg \
    --option="disable netbios = yes" \
    --option="allow dns updates = nonsecure" \
    --option="ldap server require strong auth = no"
    ln -s /var/lib/samba/private/krb5.conf /etc/krb5.conf

fi
if [ "$mode" = join ]; then
    getpasswd high
cat <<EOF >/etc/krb5.conf
[libdefaults]
    default_realm = $realm
    dns_lookup_realm = false
    dns_lookup_kdc = true
EOF
  samba-tool domain join $domain DC \
  -UAdministrator --password="$pass"
fi

for cmd in unmask enable start; do systemctl $cmd samba-ad-dc; done
exit
