#!/usr/bin/env bash

# Copyright (c) Microsoft Corporation.
#
# Adapted from gsasl autopkgtests from
# https://salsa.debian.org/debian/gsasl/-/blob/2ead79423c14d21b4ab05f016e8c6583d7afbe15/tests/gsasl-dovecot-gssapi.sh,
# Copyright (C) 2022-2026 Simon Josefsson
#
# 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 3 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, see <http://www.gnu.org/licenses/>.

set -e
set -u
set -x

# Set up local KDC

export PATH=$PATH:/sbin:/usr/sbin

cat<<EOF > /etc/krb5kdc/kdc.conf
[kdcdefaults]
    kdc_ports = 750,88

[realms]
    KRB5.TEST = {
        database_name = /var/lib/krb5kdc/principal
        admin_keytab = FILE:/etc/krb5kdc/kadm5.keytab
        acl_file = /etc/krb5kdc/kadm5.acl
        key_stash_file = /etc/krb5kdc/stash
        kdc_ports = 750,88
        max_life = 10h 0m 0s
        max_renewable_life = 7d 0h 0m 0s
        #master_key_type = aes256-cts
        #supported_enctypes = aes256-cts:normal aes128-cts:normal
        default_principal_flags = +preauth
    }

EOF

cat<<EOF > /etc/krb5.conf
[libdefaults]
	default_realm = KRB5.TEST

[domain_realm]
	.`hostname -d` = KRB5.TEST

[realms]
	KRB5.TEST = {
		kdc = `hostname -f`
	}
EOF

kdb5_util -P foo create -s
kadmin.local addprinc -randkey imap/`hostname -f`
kadmin.local addprinc -pw bar $USER
kadmin.local ktadd -k /etc/dovecot.keytab imap/`hostname -f`
chgrp dovecot /etc/dovecot.keytab
chmod 440 /etc/dovecot.keytab

systemctl restart krb5-admin-server.service krb5-kdc.service

i=0
while ! (ss -na || netstat -na) | grep 0.0.0.0:88 | grep LISTEN; do
    i=`expr $i + 1`
    test "$i" = "10" && exit 1
    sleep 1
done

echo bar | kinit $USER

exit 0
