#!/bin/sh

if ! grep -q '^ default_realm = WILLOWBARRACO.FR' /etc/krb5.conf; then
	cat <<EOF >> /etc/krb5.conf
[libdefaults]
 default_realm = WILLOWBARRACO.FR
EOF
fi

if ! grep -q '^ WILLOWBARRACO.FR = {' /etc/krb5.conf; then
	cat <<EOF >> /etc/krb5.conf
[realms]
 WILLOWBARRACO.FR = {
  kdc = kerberos.willowbarraco.fr
  admin_server = kerberos.willowbarraco.fr
 }
EOF
fi

HOSTNAME="$(hostname)"
if ! kinit -k -p "host/$HOSTNAME@WILLOWBARRACO.FR" > /dev/null 2>&1; then
	cat <<EOF >&2
You should now configure the host keytab ticket:
$ doas kadmin -p admin/admin@WILLOWBARRACO.FR
$   addprinc -randkey host/$HOSTNAME@WILLOWBARRACO.FR
$   ktadd host/$HOSTNAME@WILLOWBARRACO.FR
EOF
fi

if [ -r /etc/pam.d/swaylock ]; then
	if grep -q '^-auth            sufficient      pam_krb5.so minimum_uid=1000' /etc/pam.d/swaylock; then
		sed -i '/-auth            sufficient      pam_krb5.so minimum_uid=1000/d' /etc/pam.d/swaylock
		cat <<-EOF >> /etc/pam.d/swaylock
		-auth            optional      pam_krb5.so minimum_uid=1000 use_first_pass
		EOF
	elif ! grep -q '^-auth            optional      pam_krb5.so minimum_uid=1000 use_first_pass' /etc/pam.d/swaylock; then
		cat <<-EOF >> /etc/pam.d/swaylock

		# Unlock krb5 session
		-auth            optional      pam_krb5.so minimum_uid=1000 use_first_pass
		EOF
	fi
fi
