#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: "Verify that SID of native Windows joined is correct in S4 and OpenLDAP"
## bugs: [37572, 36570]
## tags: [basic, native_win_client]
## exposure: safe
## packages:
##  - univention-samba4
## roles:
## - domaincontroller_master
## - domaincontroller_backup
## - domaincontroller_slave
## versions:
##  4.0-0: skip

# TODO: re-enable the test after Bug #36570 is resolved.
# shellcheck source=../../lib/base.sh
. "$TESTLIBPATH/base.sh" || exit 137

RETVAL=100


echo "Looking for a Windows host. It should be joined prior to the test run:"
windows_host_dn="$(udm computers/windows list | sed -n 's/^DN: //p')"

# skip the test if no Windows host records cannot be found:
if [ -z "$windows_host_dn" ]; then
    echo "Cannot find any 'computers/windows' records via UDM (Possible reasons: There is simply no Windows in the Domain; There is a Windows client, but not joined; Or replication did not work.)"
    exit 137
fi
echo "Windows host '$windows_host_dn' will be used for the test."


# extract the Windows hostname:
windows_hostname="$(echo $windows_host_dn | sed 's/^cn=\(.*\),cn=computers,'"$ldap_base"'/\1/g')"
echo "Windows Hostname is $windows_hostname"


# check Windows hostname lookup:
dns_lookup="$(LANG=C host -t A $windows_hostname | grep 'not found')"
if [ -n "$dns_lookup" ]; then
    echo $dns_lookup
    fail_fast 110 "The Windows Client with a name $windows_hostname cannot be found in the domain (Or possibly was not joined correctly.)"
fi


# get the account data from OpenLDAP:
openldap_account_data=$(univention-ldapsearch -LLL -s base -b "$windows_host_dn" uid sambaSID)

# get the sAMAccountName equivalent from OpenLDAP:
samaccountname=$(sed -n 's/^uid: //p' <<<"$openldap_account_data")


# get the objectSid from S4:
windows_object_sid="$(univention-s4search sAMAccountName="$samaccountname" objectSid | sed -n 's/^objectSid: //p')"
echo "The Windows Host 'objectSID' in S4 is '$windows_object_sid'"
if [ -z "$windows_object_sid" ]; then
    fail_fast 110 "Failed to determine the Windows host 'objectSID' or it is empty."
fi


# get the sambaSID from OpenLDAP:
windows_samba_sid=$(sed -n 's/^sambaSID: //p' <<<"$openldap_account_data")
echo "The Windows Host sambaSID in 'OpenLDAP' is '$windows_samba_sid'"
if [ -z "$windows_samba_sid" ]; then
    fail_fast 110 "Failed to determine the Windows host 'sambaSID' or it is empty."
fi


# fail if Windows Host SID in OpenLDAP starts with temporary prefix 'S-1-4-':
if [[ $windows_samba_sid == S-1-4-* ]]; then
    fail_fast 110 "The sambaSID of the Windows '$windows_hostname' has a UCS temporary prefix."
fi


# fail if Windows Host SIDs in S4 and OpenLDAP are different:
if [ "$windows_object_sid" != "$windows_samba_sid" ]; then
    fail_fast 110 "The SIDs of '$windows_hostname' are not the same in Samba4 '$windows_object_sid' and OpenLDAP '$windows_samba_sid'."
fi   


exit $RETVAL
