#!/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 | DN1)"
[ -n "$windows_host_dn" ] ||
    fail_fast 137 "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.)"
echo "Windows host '$windows_host_dn' will be used for the test."


# extract the Windows hostname:
# shellcheck disable=SC2001
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:
LANG=C host -t A "$windows_hostname" | grep 'not found' &&
    fail_fast 110 "The Windows Client with a name $windows_hostname cannot be found in the domain (Or possibly was not joined correctly.)"


# 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=$(VAL uid <<<"$openldap_account_data")


# get the objectSid from S4:
windows_object_sid="$(univention-s4search sAMAccountName="$samaccountname" objectSid | VAL objectSid)"
echo "The Windows Host 'objectSID' in S4 is '$windows_object_sid'"
[ -n "$windows_object_sid" ] ||
    fail_fast 110 "Failed to determine the Windows host 'objectSID' or it is empty."


# get the sambaSID from OpenLDAP:
windows_samba_sid=$(VAL sambaSID <<<"$openldap_account_data")
echo "The Windows Host sambaSID in 'OpenLDAP' is '$windows_samba_sid'"
[ -n "$windows_samba_sid" ] ||
    fail_fast 110 "Failed to determine the Windows host 'sambaSID' or it is empty."


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


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


exit $RETVAL
