#!/bin/bash
# -*- coding: utf-8 -*-
#
# Univention UCS@school
#
# Copyright 2014-2017 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

. /usr/share/univention-lib/all.sh

display_help() {
	cat <<-EOL
	Syntax:
	  $0 [options] "<IP of UCS@school DC>"

	Options:
	  --dcaccount <account>:    Name of Administrator account
	  --dcpwd <password file>:  File with DC master password
	  --rootpassword <file>:    File with root password of UCS@school Samba4 Slave
	  -h | --help | -?:         Print this usage message and exit program

	Description:
	  $0 installs Samba4 on a second Slave DC and joins it to an UCS@school DC
	  The script must be called with IP of a UCS@school DC running the S4 Connector service

	EOL
}

eval "$(univention-config-registry shell)"

if [ "$server_role" != "domaincontroller_slave" ]; then
	echo "This script can only be run on a DC Slave"
	exit 1
fi

USERTMP="$(mktemp -d)"
DCPWD="$USERTMP/dcpwd"
ROOTPWD="$USERTMP/rootpwd"
JOIN_LOGFILE="/var/log/univention/join-secondary-samba4.log"
set -o pipefail

trapOnExit() {
	rm -rf "$USERTMP"
	echo "$(LC_ALL=C date): finish $0" >>"$JOIN_LOGFILE" 2>&1
	exit "$rc"
}

trap trapOnExit EXIT

echo "$(LC_ALL=C date): starting $0 $*" >>"$JOIN_LOGFILE" 2>&1

while [ $# -gt 0 ]
do
	case "$1" in
		"--dcaccount")
			DCACCOUNT="${2:?missing DC master account}"
			shift 2 || exit 2
			;;
		"--dcpwd")
			dcpwd="${2:?missing DC password file}"
			shift 2 || exit 2
			cp "$dcpwd" "$DCPWD" || exit 2
			;;
		"--rootpassword")
			rootpwd="${2:?missing root password}"
			cp "$rootpwd" "$ROOTPWD" || exit 2
			shift 2 || exit 2
			;;
		"--help"|"-h"|"-?")
			display_help
			exit 0
			;;
		-*)
			display_help
			exit 1
			;;
		*)
			if [ -z "$target_school_dc_ip" ]; then
				target_school_dc_ip="$1"
				shift
			else
				display_help
				exit 1
			fi
			;;
	esac
done
if [ -z "$target_school_dc_ip" ]; then
	display_help
	exit 1
fi

test_school_role=$(univention-ldapsearch -xLLL "(univentionService=UCS@school)" -b "$ldap_hostdn" -s base dn 2>/dev/null | ldapsearch-wrapper | ldapsearch-decode64  | sed -n 's/^dn: //p')

if [ -n "$test_school_role" ]; then
	echo "This system is a UCS@school DC. This script can only be run on a non UCS@school DC"
	exit 1
fi


if [ -z "$DCACCOUNT" ]; then
	echo -n "Enter DC Master Account : "
	read DCACCOUNT
fi
if [ ! -f "$DCPWD" ]; then
	touch "$DCPWD"
	chmod 600 "$DCPWD"
	echo -n "Enter DC Master Password: "
	read -s password
	echo -n "$password" >>"$DCPWD"
	echo ""
	echo ""
fi
bindpwd=$(<"$DCPWD")

if [ ! -f "$ROOTPWD" ]; then
	touch "$ROOTPWD"
	chmod 600 "$ROOTPWD"
	echo -n "Enter Root Password of UCS@school Samba4 DC: "
	read -s password
	echo -n "$password" >>"$ROOTPWD"
	echo ""
	echo ""
fi

{	## start logging

echo -n "Trying ssh access too root@$target_school_dc_ip : "
if ! target_school_dc_server_role=$(univention-ssh "$ROOTPWD" root@"$target_school_dc_ip" /usr/sbin/ucr get server/role); then
	echo -e "\033[60Gfailed"
	exit 1
else
	if [ "$target_school_dc_server_role" = "domaincontroller_slave" ] \
		|| [ "$target_school_dc_server_role" = "domaincontroller_master" ]; then
		echo -e "\033[60Gdone"
	else
		echo -e "\033[60Gfailed"
		echo "The server $target_school_dc_ip has an invalid role: '$target_school_dc_server_role'"
		exit 1
	fi
fi


echo -n "Search LDAP binddn : "
binddn="$(univention-ssh "$ROOTPWD" "root@${target_school_dc_ip}" \
	/usr/sbin/udm users/user list --filter uid="$DCACCOUNT" --logfile /dev/null | sed -ne 's|^DN: ||p')"

if [ -z "$binddn" ]; then
	echo -e "\033[60Gfailed"
	echo "binddn for user $DCACCOUNT not found. "
	exit 1
else
	echo -e "\033[60Gdone"
fi

echo -n "Search school server binddn : "
target_server_udm_output=$(univention-ssh "$ROOTPWD" "root@${target_school_dc_ip}" \
	/usr/sbin/udm "computers/$target_school_dc_server_role" list --filter "\'(&(service=UCS@school)(service=S4 SlavePDC)(service=S4 Connector)(ip=$target_school_dc_ip))\'")
target_school_dc_hostdn=$(echo "$target_server_udm_output" | sed -n 's/^DN: //p')
target_school_dc_name=$(echo "$target_server_udm_output" | sed -n 's/^ *name: //p')
if [ -z "$target_school_dc_hostdn" ]; then
	echo -e "\033[60Gfailed"
	echo "Could not verify that $target_school_dc_ip is a UCS@school DC running the S4 Connector and SlavePDC service"
	exit 1
else
	echo -e "\033[60Gdone"
fi

echo -n "School server type : "
target_server_ucsschool_service=''
while read service; do
	case "$service" in
		"UCS@school Education")
			target_server_ucsschool_type=Edukativnetz
			target_server_ucsschool_service="$service"
			;;
		"UCS@school Administration")
			target_server_ucsschool_type=Verwaltungsnetz
			target_server_ucsschool_service="$service"
			;;
	esac
done < <(echo "$target_server_udm_output" | sed -n 's/^ *service: //p')
if [ -z "$target_server_ucsschool_service" ]; then
	echo -e "\033[60Gfailed"
	echo "Could not determine UCS@school server type of $target_school_dc_ip."
	exit 1
else
	echo -e "\033[60G$target_server_ucsschool_service"
fi

if [ "$target_school_dc_server_role" = "domaincontroller_slave" ]; then
	echo -n "Determine school OU of school server : "	## check with given Admin credentials, to verify them
	target_school_ou=$(univention-ssh "$DCPWD" "${DCACCOUNT}@${target_school_dc_ip}" \
		". /usr/share/ucs-school-lib/base.sh; school_ou '$target_school_dc_hostdn'")

	if [ -z "$target_school_ou" ]; then
		echo -e "\033[60Gfailed"
		echo "ERROR: Could not determine school OU of the remote school DC."
		exit 1
	else
		echo -e "\033[60G$target_school_ou"
	fi

	echo -n "Verify LDAP hostdn : "
	target_ldap_hostdn="$(univention-ssh "$ROOTPWD" "root@${target_school_dc_ip}" \
		/usr/sbin/udm computers/domaincontroller_slave list --filter name="$hostname" --logfile /dev/null | sed -ne 's|^DN: ||p')"
	if [ -z "$target_ldap_hostdn" ]; then
		echo -e "\033[60Gfailed"
		echo "Could not verify ldap/hostdn for local DC."
		echo "First the host account $hostname needs to be moved to the school OU it should join to."
		exit 1
	else
		echo -e "\033[60Gdone"
	fi

	echo -n "Search school OU : "	## check with given Admin credentials, to verify them
	my_school_ou=$(univention-ssh "$DCPWD" "${DCACCOUNT}@${target_school_dc_ip}" \
		". /usr/share/ucs-school-lib/base.sh; school_ou '$target_ldap_hostdn'")

	if [ -z "$my_school_ou" ]; then
		echo -e "\033[60Gfailed"
		echo "Could not determine school OU for local DC."
		echo "First the host account $hostname needs to be moved to the school OU it should join to."
		exit 1
	else
		echo -e "\033[60G$my_school_ou"
	fi

	if [ "$target_school_ou" != "$my_school_ou" ]; then
		echo "ERROR: The account of this server $hostname is located below $my_school_ou"
		echo "        but the server $target_school_dc_ip is in $target_school_ou."
		exit 1
	fi

	echo -n "Check group memberschip : "
	test_output=$(univention-ssh "$ROOTPWD" "root@${target_school_dc_ip}" \
		/usr/sbin/udm groups/group list --filter name="DC-$target_server_ucsschool_type" | sed -n "/^ *hosts: $target_ldap_hostdn$/p")
	if [ -z "$test_output" ]; then
		echo -e "\033[60Gfailed"
		echo "$hostname is not member of the group DC-$target_server_ucsschool_type, this needs to be fixed first manually."
		exit 1
	fi
	test_output=$(univention-ssh "$ROOTPWD" "root@${target_school_dc_ip}" \
		/usr/sbin/udm groups/group list --filter name="OU$my_school_ou-DC-$target_server_ucsschool_type" | sed -n "/^ *hosts: $target_ldap_hostdn$/p")
	if [ -z "$test_output" ]; then
		echo -e "\033[60Gfailed"
		echo "$hostname is not member of the group OU$my_school_ou-DC-$target_server_ucsschool_type, this needs to be fixed first manually."
		exit 1
	else
		echo -e "\033[60Gdone"
	fi
fi

echo "$(LC_ALL=C date): $0 pre-checks done" >>"$JOIN_LOGFILE" 2>&1

if [ -x /usr/bin/rdate ]; then
	echo -n "Sync time "
	/usr/bin/rdate "$target_school_dc_ip" >/dev/null 2>&1
	echo -e "\033[60Gdone"
fi

ucr commit /etc/apt/sources.list.d/*
# Cannot use univention-install here as it's interactive:  univention-install univention-samba4 || exit 1
(
LOGFILE="/var/log/univention/actualise.log"
export DEBIAN_FRONTEND=noninteractive
echo "***** Starting \"univention-install $@\" on $(date)" >> "$LOGFILE"
set -e
set -o pipefail
$update_commands_update 2>&1 | tee -a "$LOGFILE"
exec $update_commands_install univention-samba4 2>&1 | tee -a "$LOGFILE"
) || exit 1

. /usr/share/univention-samba4/lib/all.sh

eval "$(univention-ssh "$ROOTPWD" root@"$target_school_dc_ip" \
	ucr shell ldap/hostdn samba4/join/site | sed -n 's/^/target_school_/p')"

if [ -n "$target_school_samba4_join_site" ]; then
	ucr set samba4/join/site="$target_school_samba4_join_site"
fi

master_hostname="$(echo $ldap_master | cut -d '.' -f 1)"
ucr set \
	nameserver1="$target_school_dc_ip" \
	samba4/dc="$target_school_dc_ip" \
	samba4/ldb/sam/module/prepend="univention_samaccountname_ldap_check" \
	samba4/addmachine?deny \
	directory/manager/samba3/legacy?yes \
	dns/register/srv_records/kerberos?false \
	dns/register/srv_records/ldap?false \
	samba4/dns/domain/register?false \
	samba4/join/dnsupdate?true \
	samba/share/sysvol/readonly?no \
	samba4/sysvol/sync/host?"$target_school_dc_name" ## Workaround for Bug #34905  # Don''t use the FQDN, Bug #27247

ucr unset nameserver2 nameserver3

## In case this script is run a second time, e.g. to rejoin, we have to re-enable local account creation to re-create the dns-$hostname account
ucr set --forced samba4/ldb/sam/module/prepend=''	## This shadows the value above, will be unset later to let the usual value re-surface.

stop_udm_cli_server	## to make it pick up the modified directory/manager/samba3/legacy

## Workaround for Bug #34908
samba_krb5conf_template="/usr/share/samba/setup/krb5.conf"
dpkg-divert --quiet --rename --local --divert "${samba_krb5conf_template}.debian" --add "${samba_krb5conf_template}"
cp "${samba_krb5conf_template}.debian" "${samba_krb5conf_template}"
cat >> "${samba_krb5conf_template}" <<%EOF

[realms]
\${REALM} = {
	kdc = 127.0.0.1
}
%EOF

## Workaround for Bug #34754
if [ -r /var/lib/samba/private/sam.ldb ]; then
	ridset_dn=$(univention-s4search sAMAccountName="$hostname$" rIDSetReferences  | ldapsearch-wrapper | sed -n 's/^rIDSetReferences: //p')
	if [ -n "$ridset_dn" ]; then
		test_output=$(univention-s4search -s base -b "$ridset_dn" | ldapsearch-wrapper)
		old_rIDAllocationPool=$(sed -n 's/^rIDAllocationPool: //p' <<<"$test_output")
		old_rIDPreviousAllocationPool=$(sed -n 's/^rIDPreviousAllocationPool: //p' <<<"$test_output")
		old_rIDNextRID=$(sed -n 's/^rIDNextRID: //p' <<<"$test_output")
	fi
fi

## append dns-$hostname to connector/s4/mapping/user/ignorelist on remote host
test_output=$(univention-ssh "$ROOTPWD" root@"$target_school_dc_ip" \
	/usr/sbin/ucr get connector/s4/mapping/user/ignorelist)
ignored_users=( $(sed -e 's/,/ /g' <<<"$test_output") )
found=''
for str in "${ignored_users[@]}"; do
	if [ "$str" = "dns-$hostname" ]; then
		found=1
		break
	fi
done
if [ -z "$found" ]; then
	univention-ssh "$ROOTPWD" root@"$target_school_dc_ip" \
		/usr/sbin/ucr set connector/s4/mapping/user/ignorelist="$test_output,dns-$hostname"
fi

########### core join start
trapOnExit2() {
	trap '' SIGINT
	univention-ssh "$ROOTPWD" root@"$target_school_dc_ip" \
	"/usr/share/univention-samba4/scripts/register_ldb_module.py -H /var/lib/samba/private/sam.ldb --ignore-exists --prepend=univention_samaccountname_ldap_check && /etc/init.d/samba-ad-dc restart"
	trapOnExit
}

trap trapOnExit2 EXIT

univention-ssh "$ROOTPWD" root@"$target_school_dc_ip" \
	"/usr/sbin/ucr set samba4/service/drepl=true; /usr/share/univention-samba4/scripts/register_ldb_module.py -H /var/lib/samba/private/sam.ldb --ignore-exists --remove=univention_samaccountname_ldap_check && /etc/init.d/samba-ad-dc restart; /etc/init.d/univention-s4-connector restart"

univention-join -dcaccount "$DCACCOUNT" -dcpwd "$DCPWD"
echo "**************************************************************************"
echo "* INFO: In case 98univention-samba4slavepdc-dns.inst failed, this is ok"
echo "*       for rejoins and will be retried in a couple of seconds below."
echo "**************************************************************************"

univention-ssh "$ROOTPWD" root@"$target_school_dc_ip" \
	"/usr/share/univention-samba4/scripts/register_ldb_module.py -H /var/lib/samba/private/sam.ldb --ignore-exists --prepend=univention_samaccountname_ldap_check && /etc/init.d/samba-ad-dc restart"

trap trapOnExit EXIT
########### core join end

eval "$(univention-config-registry shell)"

### Workaround for "Bad DSA objectGUID <GUID> for sid <UDM sid>  - expected sid <Samba sid>" during replication in log.samba
## * this seems to be due to directory/manager/samba3/legacy=yes and S4 Connector overwriting the temporary Samba SID
## * the DRS replication code finds the temporary Samba SID still present in the extended DN blob of the serverReference attribute
## * let's rewrite it to the correct value:
my_sid=$(univention-ldapsearch -x -b "$ldap_hostdn" sambaSID | sed -n 's/^sambaSID: //p')
echo "Checking my SID '$my_sid' in the remote Samba4:"
univention-ssh --no-split "$ROOTPWD" "root@${target_school_dc_ip}" \
        'TMP_SCRIPT=$(mktemp) && trap "rm -f \"$TMP_SCRIPT\"" EXIT && cat >"$TMP_SCRIPT" && /usr/bin/python2.7 "$TMP_SCRIPT" && /etc/init.d/samba-ad-dc restart' \
	<<%EOF
#!/usr/bin/python
import ldb
from samba.auth import system_session
from samba.param import LoadParm
from samba import Ldb
from samba.ndr import ndr_pack, ndr_unpack
from samba.dcerpc import security
import sys

lp = LoadParm()
lp.load('/etc/samba/smb.conf')

sam_ldb = Ldb('/var/lib/samba/private/sam.ldb', session_info=system_session(), lp=lp)

res = sam_ldb.search(sam_ldb.get_default_basedn(), scope=ldb.SCOPE_SUBTREE, expression="(&(sAMAccountName=$hostname$)(objectSid=$my_sid))", attrs = ["objectSid", "serverReferenceBL"])
if len(res.msgs) == 0:
	print "ERROR: SID '$my_sid' not found associated with $hostname in Samba4 on $target_school_dc_ip"
	res = sam_ldb.search(sam_ldb.get_default_basedn(), scope=ldb.SCOPE_SUBTREE, expression="(sAMAccountName=$hostname$)", attrs = ["objectSid",])
	if len(res.msgs) != 0:
		print "       Found instead: %s" % (ndr_unpack(security.dom_sid, res.msgs[0]["objectSid"][0]),)
		print "ADVICE:Check output of univention-s4connector-list-rejected on $target_school_dc_ip"
	sys.exit(1)

record = res.msgs[0]
sid1_ndr = record["objectSid"][0]
sid1_str = ndr_unpack(security.dom_sid, sid1_ndr)
print "$hostname objecSid:\t%s" % (sid1_str,)

if "serverReferenceBL" in record:
	res = sam_ldb.search(base=record["serverReferenceBL"][0], scope=ldb.SCOPE_BASE, expression="(objectClass=server)", attrs = ["serverReference"], controls=["extended_dn:0"])
	record = res.msgs[0]
	serverReference_str = record["serverReference"][0]
	serverReference_Dn = ldb.Dn(sam_ldb, record["serverReference"][0])
	sid2_ndr = serverReference_Dn.get_extended_component("SID")
	sid2_str = ndr_unpack(security.dom_sid, sid2_ndr)
	print "serverRefrence SID:\t%s" % (sid2_str,)
	if sid2_str != sid1_str:
		print "Fixing serverRefrence SID."
		msg = ldb.Message()
		msg.dn = record.dn
		serverReference_Dn.set_extended_component("SID", sid1_ndr)
		msg["serverReference"] = ldb.MessageElement( [ serverReference_Dn.extended_str() ] , ldb.FLAG_MOD_REPLACE, "serverReference")
		sam_ldb.modify(msg)

		res = sam_ldb.search(base=record.dn, scope=ldb.SCOPE_BASE, expression="(objectClass=server)", attrs = ["serverReference"], controls=["extended_dn:0"])
		record = res.msgs[0]
		serverReference_str = record["serverReference"][0]
		serverReference_Dn = ldb.Dn(sam_ldb, record["serverReference"][0])
		sid2_ndr = serverReference_Dn.get_extended_component("SID")
		sid2_str = ndr_unpack(security.dom_sid, sid2_ndr)
		print "serverRefrence SID:\t%s" % (sid2_str,)
	else:
		sys.exit(2)
%EOF


## Workaround for Bug #34754
if [ -r /var/lib/samba/private/sam.ldb ]; then
	ridset_dn=$(univention-s4search sAMAccountName="$hostname$" rIDSetReferences  | ldapsearch-wrapper | sed -n 's/^rIDSetReferences: //p')
	if [ -n "$ridset_dn" ]; then
		test_output=$(univention-s4search -s base -b "$ridset_dn" | ldapsearch-wrapper)
		new_rIDAllocationPool=$(sed -n 's/^rIDAllocationPool: //p' <<<"$test_output")
		new_rIDPreviousAllocationPool=$(sed -n 's/^rIDPreviousAllocationPool: //p' <<<"$test_output")
		new_rIDNextRID=$(sed -n 's/^rIDNextRID: //p' <<<"$test_output")
	fi
fi
if [ -n "$new_rIDAllocationPool" ] && [ -z "$new_rIDNextRID" ]; then
	if [ "$new_rIDAllocationPool" = "$old_rIDAllocationPool" ] && [ -n "$old_rIDNextRID" ]; then
		{
		cat <<-%EOF
		dn: $ridset_dn
		changetype: modify
		add: rIDNextRID
		rIDNextRID: $old_rIDNextRID
		%EOF

		if [ -z "$new_rIDPreviousAllocationPool" ]; then
			if [ -n "$old_rIDPreviousAllocationPool" ]; then
				cat <<-%EOF
				-
				add: rIDPreviousAllocationPool
				rIDPreviousAllocationPool: $old_rIDPreviousAllocationPool
				%EOF
			else
				cat <<-%EOF
				-
				add: rIDPreviousAllocationPool
				rIDPreviousAllocationPool: $new_rIDAllocationPool
				%EOF
			fi
		fi
		} | ldbmodify -H /var/lib/samba/private/sam.ldb
	fi
fi

# Remove own values from kerberos SRV records
if ! is_ucr_true dns/register/srv_records/kerberos; then
	/usr/share/univention-directory-manager-tools/univention-dnsedit --binddn "$binddn" --bindpwd "$bindpwd" --ignore-exists $domainname remove srv kerberos tcp 0 100 88 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --binddn "$binddn" --bindpwd "$bindpwd" --ignore-exists $domainname remove srv kerberos udp 0 100 88 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --binddn "$binddn" --bindpwd "$bindpwd" --ignore-exists "$domainname" remove srv kerberos "tcp.dc._msdcs" 0 100 88 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --binddn "$binddn" --bindpwd "$bindpwd" --ignore-exists "$domainname" remove srv kpasswd "tcp" 0 100 464 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --binddn "$binddn" --bindpwd "$bindpwd" --ignore-exists "$domainname" remove srv kpasswd "udp" 0 100 464 "$hostname.$domainname."
fi

# Remove own values from ldap SRV records
if ! is_ucr_true dns/register/srv_records/ldap; then
	/usr/share/univention-directory-manager-tools/univention-dnsedit --binddn "$binddn" --bindpwd "$bindpwd" --ignore-exists "$domainname" remove srv ldap tcp 0 100 7389 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --binddn "$binddn" --bindpwd "$bindpwd" --ignore-exists "$domainname" remove srv ldap tcp 0 100 389 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --binddn "$binddn" --bindpwd "$bindpwd" --ignore-exists "$domainname" remove srv ldap "tcp.pdc._msdcs" 0 100 389 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --binddn "$binddn" --bindpwd "$bindpwd" --ignore-exists "$domainname" remove srv ldap "tcp.dc._msdcs" 0 100 389 "$hostname.$domainname."
fi

############# start run-jounscripts #2
#### In case Bug #34754 or the "Bad DSA objectGUID" issue hit us, 98univention-samba4-dns.inst may have failed.
univention-run-join-scripts -dcaccount "$DCACCOUNT" -dcpwd "$DCPWD" --force --run-scripts 98univention-samba4-dns.inst
############# end run-jounscripts #2


############# start run-jounscripts #3
## Finally, we have to install libunivention-ldb-modules and run its joinscripts (cannot to univention-add-app before initial join)
ucr unset --forced samba4/ldb/sam/module/prepend	## this restores the regular value set above.
univention-add-app ucsschool -l libunivention-ldb-modules || exit 1
#### And run the joinscripts from this package, some with --force:
univention-run-join-scripts -dcaccount "$DCACCOUNT" -dcpwd "$DCPWD" --run-scripts 96univention-samba4slavepdc.inst
#### And run the other Joinscripts, we need to --force here: In the re-join case samba4/ldb/sam/module/prepend needs to be evaluated now:
univention-run-join-scripts -dcaccount "$DCACCOUNT" -dcpwd "$DCPWD" --force --run-scripts 97libunivention-ldb-modules.inst
#### In case Bug #34754 or the "Bad DSA objectGUID" issue hit us, 98univention-samba4slavepdc-dns.inst will have failed (on re-join)
univention-run-join-scripts -dcaccount "$DCACCOUNT" -dcpwd "$DCPWD" --force --run-scripts 98univention-samba4slavepdc-dns.inst
############# end run-jounscripts #3

ucs_addServiceToLocalhost "$target_server_ucsschool_service" --binddn "$binddn" --bindpwdfile "$DCPWD"	## required for the ucsschool-s4-branch-site listener

echo
echo "**************************************************************************"
univention-check-join-status
rc=$?
echo "**************************************************************************"
echo

exit "$rc"
} 2>&1 | tee -a "$JOIN_LOGFILE"
rc=$?	## for trapOnExit
