#!/bin/bash

#set -e ==> attention aux tests !

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

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

function usage
{
    echo "Usage :"
    [[ -n $1 ]] && echo -e "\n${@}\n"
    echo "   $(basename $0) <nom_serveur> [<ip>]"
    exit 2
}

function set_dns_srv_entry ()
{
    zone="${1}"
    entry="${2}.${zone}"
    server="${3}"
    shift 3
    data="${server} $@"
    dig +noall +answer -t SRV @${DNS_DC1} ${entry} | grep -qi ${server}
    res=$?
    if [[ ${res} -eq 0 ]]
    then
        echo "Entry ${entry} already set for server ${server}"
    else
        echo "Create missing DNS entry ${entry} for server ${server}"
        samba-tool dns add "${AD_HOST_NAME}" "${zone}" "${entry}" SRV "${data}"
    fi
}

[[ -z $1 ]] && usage "Missing nom_serveur"
[[ -z $2 ]] && usage "Missing ip"

NAME=$1
IP=$2
SITE=$3
MODE=$4

DNS_DC1=${AD_HOST_NAME}.${AD_REALM}
DNS_DC2=${NAME}.${AD_REALM}
BASEDN="$(echo DC=${AD_REALM//./,DC=})"


# export keytab Administrator
[[ -f "${AD_HOST_KEYTAB_FILE}" ]] && rm "${AD_HOST_KEYTAB_FILE}"
samba-tool domain exportkeytab "${AD_HOST_KEYTAB_FILE}" --principal="${AD_HOST_NAME^^}@${AD_REALM^^}"
if [[ "$?" -ne 0 ]]
then
echo "Impossible de générer le keytab ${AD_HOST_NAME}"
exit 1
fi
kinit "${AD_HOST_NAME^^}@${AD_REALM^^}" -k -t "${AD_HOST_KEYTAB_FILE}"

host -t A "${DNS_DC2}."
RES=$?
if [ $RES -ne 0 ]
then
    samba-tool dns add "${AD_HOST_NAME}" "${AD_REALM}" "${NAME}" A "${IP}"
else
    echo "${IP} : Déjà inscrit!"
fi

if [ "$MODE" = "RODC" ]
then
    set_dns_srv_entry "${AD_REALM}" "_ldap._tcp.${SITE}._sites" "${DNS_DC2}" 389 0 100
    set_dns_srv_entry "${AD_REALM}" "_kerberos._tcp.${SITE}._sites" "${DNS_DC2}" 88 0 100
    set_dns_srv_entry "${AD_REALM}" "_gc._tcp.${SITE}._sites" "${DNS_DC2}" 3268 0 100
    set_dns_srv_entry "_msdcs.${AD_REALM}" "_ldap._tcp.${SITE}._sites.dc" "${DNS_DC2}" 389 0 100
    set_dns_srv_entry "_msdcs.${AD_REALM}" "_kerberos._tcp.${SITE}._sites.dc" "${DNS_DC2}" 88 0 100
    set_dns_srv_entry "_msdcs.${AD_REALM}" "_ldap._tcp.${SITE}._sites.gc" "${DNS_DC2}" 3268 0 100
fi

objectGuidRecord=$(ldbsearch -H /var/lib/samba/private/sam.ldb -b "CN=NTDS Settings,CN=${NAME^^},CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,${BASEDN}" '(invocationId=*)' --cross-ncs objectGuid | grep -i "objectGuid:")
objectGuid=$(echo "$objectGuidRecord" | awk '{print $2}')
if [ -n "$objectGuid" ]
then
    host -t CNAME "$objectGuid._msdcs.${AD_REALM}."
    RES=$?
    if [ $RES -ne 0 ]
    then
        samba-tool dns add "${AD_HOST_NAME}" "_msdcs.${AD_REALM}" "$objectGuid" CNAME "${DNS_DC2}"
    fi
fi

