#!/bin/bash
# -*- coding: utf-8 -*-
#
# Univention UCS@School
#
# Copyright 2014 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
. /usr/share/ucs-school-lib/base.sh

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

	Options:
	  --dcaccount <account>:          Name of DC master account
	  --dcpwd <password file>:        File with DC master password
	  --rootpassword <fqdn>:          Root Password of UCS@school Samba4 DC
	  -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

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

echo "$(LC_ALL=C date): starting $0 $*" >>/var/log/univention/join.log 2>&1

if ! ldapsearch -xLLL -h "$target_school_dc_ip" -p 7389 -s base -b "$ldap_base" -D "$ldap_hostdn" -y /etc/machine.secret >/dev/null 2>&1; then
	echo "The DC Slave needs to be joined first without Samba4 or UCS@school installed"
	exit 1
fi

test_school_role=$(univention-ldapsearch -xLLL "(univentionService=UCS@school)" -b "$ldap_hostdn" -s base dn | 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

USERTMP="$(mktemp -d)"
DCPWD="$USERTMP/dcpwd"
ROOTPWD="$USERTMP/rootpwd"

trapOnExit() {
	rm -rf "$USERTMP"
	echo "$(LC_ALL=C date): finish $0" >>/var/log/univention/join.log 2>&1
}

trap trapOnExit EXIT


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
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

echo -n "Search LDAP binddn : "
binddn=$(univention-ldapsearch -xLLL "(&(objectClass=posixAccount)(uid=$DCACCOUNT))" | ldapsearch-wrapper | ldapsearch-decode64  | sed -n 's/^dn: //p')
if [ -z "$binddn" ]; then
	echo "binddn for user $DCACCOUNT not found. "
	exit 1
fi
echo " [done]."


target_school_dc_hostdn=$(univention-ldapsearch -xLLL "(&(univentionService=UCS@school)(univentionService=S4 Connector)(aRecord=$target_school_dc_ip))" dn | ldapsearch-wrapper | ldapsearch-decode64  | sed -n 's/^dn: //p')

if [ -z "$target_school_dc_hostdn" ]; then
	echo "Could not verify that $target_school_dc_ip is a UCS@school DC running the S4 Connector service"
	exit 1
fi

echo -n "Trying ssh access too root@$target_school_dc_hostdn : "
if test_output=$(univention-ssh "$ROOTPWD" root@"$target_school_dc_ip" ucr get ldap/hostdn); then
	if [ "$test_output" != "$target_school_dc_hostdn" ]; then
		echo "ERROR: univention-ssh "$target_school_dc_ip" ucr get ldap/hostdn returned $test_output"
		echo "       expected: $target_school_dc_hostdn"
		exit 1
	fi
else
	echo "ssh access to root@$target_school_dc_hostdn failed"
	exit 1
fi

target_school_ou=$(school_ou "$target_school_dc_hostdn")

echo "$(LC_ALL=C date): start $0" >>/var/log/univention/join.log 2>&1

univention-install univention-samba4 || exit 1
univention-add-app ucsschool -l libunivention-ldb-modules || 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" \
	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?"$master_hostname" # Don''t use the FQDN, Bug #27247

ucr unset nameserver2 nameserver3

# 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 "$@" --ignore-exists $domainname remove srv kerberos tcp 0 100 88 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit "$@" --ignore-exists $domainname remove srv kerberos udp 0 100 88 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit "$@" --ignore-exists "$domainname" remove srv kerberos "tcp.dc._msdcs" 0 100 88 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit "$@" --ignore-exists "$domainname" remove srv kpasswd "tcp" 0 100 464 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit "$@" --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 "$@" --ignore-exists "$domainname" remove srv ldap tcp 0 100 7389 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit "$@" --ignore-exists "$domainname" remove srv ldap tcp 0 100 389 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit "$@" --ignore-exists "$domainname" remove srv ldap "tcp.pdc._msdcs" 0 100 389 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit "$@" --ignore-exists "$domainname" remove srv ldap "tcp.dc._msdcs" 0 100 389 "$hostname.$domainname."
fi

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/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"
	
univention-join -dcaccount "$DCACCOUNT" -dcpwd "$DCPWD"

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
