#!/bin/bash

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

eval "$(ucr shell)"

check_samba_processes() {
	local samba_pids
	local comm
	local samba_process_name
	local pid
	local samba_processes
	local min_samba_processes

	if ! [ -x /usr/bin/samba-tool ]; then
		echo "ERROR: /usr/bin/samba-tool is missing"
		return 1
	fi
	samba_pids=$(samba-tool processes | tail -n +3 | grep -v winbind_server | awk '{print $2;}' | grep -v '^0$')
	for pid in $samba_pids; do
		comm=$(ps -p "$pid" -o comm=)
		if [ -z "$comm" ]; then
			samba_process_name=$(samba-tool processes --pid="$pid")
			if [ -n "$samba_process_name" ]; then
				echo "ERROR: This Samba process $pid is missing: $samba_process_name"
			fi
		fi
	done

	samba_processes=($(pgrep -f /usr/sbin/samba))
	min_samba_processes=12
	if [ "${#samba_processes[@]}" -lt "$min_samba_processes" ]; then
		echo "WARNING: Total number of /usr/sbin/samba processes lower than $min_samba_processes"
		echo "This might be ok when the Samba release is newer than this check tool."
	fi
}

check_s4_connector_listener_active() {
	if ! is_ucr_false connector/s4/autostart; then
		if is_ucr_true connector/s4/listener/disabled; then
			echo "ERROR: connector/s4/autostart is active but connector/s4/listener/disabled is active too"
		fi
	fi
}

check_for_temporary_udm_sids() {
	local output
	output=$(univention-ldapsearch -xLLL sambasid=S-1-4-* dn sambasid)
	if [ -n "$output" ]; then
		echo "ERROR: The following objects have internal UDM SIDs"
		echo "==================================================="
		echo "$output"
		echo "==================================================="
	fi
}

dpkg -C

univention-check-join-status

if [ "$server_role" = "memberserver" ]; then
	if [ -x /etc/init.d/samba ]; then
		net ads testjoin
	fi
fi

if [ -n "$samba4_role" ]; then
	wbinfo --ping
	wbinfo --ping-dc
	wbinfo --check-secret
fi

if [ "$server_role" != "${server_role#domaincontroller_}" ]; then
	if [ "$samba4_role" = "DC" ]; then
		check_samba_processes
		check_s4_connector_listener_active
		kdestroy;
		kinit -t /etc/krb5.keytab "${hostname^^}$"
		klist; kdestroy
		kinit -t /var/lib/samba/private/dns.keytab "dns-$(hostname)"
		klist; kdestroy
		samba-tool drs showrepl
		/usr/share/univention-samba4/scripts/check_essential_samba4_dns_records.sh
		ldbsearch -H ldapi:///var/lib/samba/private/ldap_priv/ldapi sAMAccountName="${hostname}$" msDS-KeyVersionNumber
		ldbsearch -H /var/lib/samba/private/secrets.ldb objectClass=primaryDomain msDS-KeyVersionNumber
		check_for_temporary_udm_sids
		# samba-tool dbcheck
	fi
fi

## Possibly offer to automatically upload this as encrypted email?
# wget -q "http://download.univention.de/download/univention-support.asc" -O - | gpg --import
# gpg --encrypt --trust-model always -a -r "support@univention.de" <Filename>
