#!/bin/bash

name=$1

if [ -z "$name" ]; then
	echo "usage: $0 <hostname>"
	exit 1
fi

eval "$(ucr shell samba4/ldap/base)"

# SID=$(univention-ldapsearch -xLLL "(&(objectClass=sambaSamAccount)(uid=$name$))" sambaSID | sed -n "s/^sambaSID: //p")
SID=$(univention-s4search "(&(objectClass=computer)(sAMAccountName=$name$))" objectSid | sed -n "s/^objectSid: //p")

if [ -z "$SID" ]; then
	echo "Machine object CN=$name not found in OpenLDAP"
	exit 1
fi

ldif=$(ldbsearch -H /var/lib/samba/private/sam.ldb "(&(objectClass=dnsNode)(DC=$name))" \
	-b "CN=MicrosoftDNS,DC=DomainDnsZones,$samba4_ldap_base" ntsecuritydescriptor \
	| ldapsearch-wrapper)

dn=$(sed -n "s/^dn: //p" <<<"$ldif")

if [ -z "$dn" ]; then
	echo "DNS object DC=$name not found in Samba/AD"
	exit 1
fi

old_ntsd=$(sed -n "s/^nTSecurityDescriptor: /nTSecurityDescriptor: /p" <<<"$ldif")

new_ntsd=$(echo "$ldif" | ldapsearch-wrapper | sed -n "s/^nTSecurityDescriptor: O:SYG:\([-a-fx0-9A-Z]*\)D:AI/nTSecurityDescriptor: O:${SID}G:\1D:AI(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;${SID})/p")

ldbmodify -H /var/lib/samba/private/sam.ldb <<%EOF
dn: $dn
changetype: modify
replace: nTSecurityDescriptor
$new_ntsd
%EOF
