#!/bin/bash

eval "$(ucr shell)"

currentValue=$(ldbsearch -H ldapi:///var/lib/samba/private/ldap_priv/ldapi -b "CN=System,$samba4_ldap_base" '(&(objectClass=secret)(CN=BCKUPKEY_PREFERRED Secret))' currentValue | ldapsearch-wrapper | sed -n 's/^currentValue:: //p')

if [ -z "$currentValue" ]; then
	echo "No BCKPKEY_PREFERRED found yet. Ok, nothing to do."
	exit 1
fi

guid=$(echo "$currentValue" | python -c 'import sys,binascii; from samba.dcerpc.misc import GUID; from samba.ndr import ndr_unpack, ndr_print; print str(ndr_unpack(GUID, binascii.a2b_base64(sys.stdin.read())))')

currentValue2=$(ldbsearch -H ldapi:///var/lib/samba/private/ldap_priv/ldapi -b "CN=System,$samba4_ldap_base" "(&(objectClass=secret)(CN=BCKUPKEY_$guid Secret))" currentValue | ldapsearch-wrapper | sed -n 's/^currentValue:: //p')

cert=$(echo "$currentValue2" | base64 -d | dd bs=1c skip=1184 | openssl x509 -text -inform DER)
certfile="$(mktemp -p "$(pwd)" "BCKUPKEY_${guid}.XXXXXXXXXX.pem")"
echo "$cert" > "$certfile"

echo "GUID: $guid"
echo "Currently active ClientWrap Backupkey certificate:"
echo "==============================================================================="
echo "$cert"
echo "==============================================================================="
echo "Wrote certificate to: $certfile"
echo
echo

bits=$(echo "$cert" | sed -n 's/.*Public-Key: (\([0-9]*\) bit)/\1/p')
if [ -z "$bits" ]; then
	echo "Failed to read number of bits in RSA Public Key, sorry."
fi

if [ "$bits" != 2048 ]; then
	echo "The currently active ClientWrap Backupkey certificate doesn't seem to have 2048 bits (only $bits)."
	echo "Disable it?"
	echo "A new one will be generated the next time a new user logs on to a freshly bootet windows client."
	read -p "Disable it? [y/n] "
	if [ "${REPLY^^}" = Y ]; then
		ldbdel -H ldapi:///var/lib/samba/private/ldap_priv/ldapi "CN=BCKUPKEY_PREFERRED Secret,CN=System,$samba4_ldap_base"
	elif [ "${REPLY^^}" != N ]; then
		echo "Invalid answer."
	fi
else
	echo "Everything ok."
fi

