#!/bin/bash

# Copyright (C) 2020 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
# Copyright (C) 2020 Wolfgang Schweer <w.schweer@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

# This script cleans up /var/lib/debian-edu/host-keytabs/. It looks into TJENER's
# LDAP tree (objectClass=dhcpHost) and removes all keytab files (and host
# principals) that don't have a dhcpHost object (anymore).
#
# Usage: <this-script>

set -e

declare -a hosts
num_hosts=0
while read KEY VALUE ; do
	case "$KEY" in
		dn:) let "num_hosts+=1" ;;
		cn:) hosts[$(($num_hosts-1))]="$VALUE" ;;
		"")
		    :
		;;
	esac
done < <(ldapsearch -xLLL "objectclass=dhcpHost")

# add gateway host manually
hosts[$num_hosts]=gateway

# and also tjener...
hosts[$num_hosts+1]=tjener

printf -v hosts_str -- ',,%q' "${hosts[@]}"
hosts_str=$(echo $hosts_str | tr 'A-Z' 'a-z')

for i in $(basename -a /var/lib/debian-edu/host-keytabs/* | sed 's#.intern.keytab##') ; do
	match_value=$(echo $i | tr 'A-Z' 'a-z')
	if [[ ! "${hosts_str},," =~ ",,$match_value,," ]]; then
		kadmin.local delprinc host/$i.intern@INTERN || true
		kadmin.local delprinc nfs/$i.intern@INTERN || true
		rm /var/lib/debian-edu/host-keytabs/$i.intern.keytab
	fi
done

exit 0
