#!/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

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

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 "Trying ssh access too root@$target_school_dc_ip : "
if ! test_output=$(univention-ssh "$ROOTPWD" root@"$target_school_dc_ip" /usr/sbin/ucr get ldap/hostdn); then
	echo "ssh access to root@$target_school_dc_ip failed"
	exit 1
else
	echo -e "\033[60Gdone"
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/domaincontroller_slave list --filter "\'(&(service=UCS@school)(service=S4 Connector)(ip=$target_school_dc_ip))\'")
target_school_dc_hostdn=$(echo "$target_server_udm_output" | sed -n 's/^DN: //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 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

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/$server_role" 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

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

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

ucr commit /etc/apt/sources.list.d/*
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 --dcaccount "$DCACCOUNT" --dcpwd "$DCPWD" --ignore-exists $domainname remove srv kerberos tcp 0 100 88 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --dcaccount "$DCACCOUNT" --dcpwd "$DCPWD" --ignore-exists $domainname remove srv kerberos udp 0 100 88 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --dcaccount "$DCACCOUNT" --dcpwd "$DCPWD" --ignore-exists "$domainname" remove srv kerberos "tcp.dc._msdcs" 0 100 88 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --dcaccount "$DCACCOUNT" --dcpwd "$DCPWD" --ignore-exists "$domainname" remove srv kpasswd "tcp" 0 100 464 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --dcaccount "$DCACCOUNT" --dcpwd "$DCPWD" --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 --dcaccount "$DCACCOUNT" --dcpwd "$DCPWD" --ignore-exists "$domainname" remove srv ldap tcp 0 100 7389 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --dcaccount "$DCACCOUNT" --dcpwd "$DCPWD" --ignore-exists "$domainname" remove srv ldap tcp 0 100 389 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --dcaccount "$DCACCOUNT" --dcpwd "$DCPWD" --ignore-exists "$domainname" remove srv ldap "tcp.pdc._msdcs" 0 100 389 "$hostname.$domainname."
	/usr/share/univention-directory-manager-tools/univention-dnsedit --dcaccount "$DCACCOUNT" --dcpwd "$DCPWD" --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/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"
	
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"

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

trap trapOnExit EXIT
