#!/bin/sh

# Copyright (C) 2022 Simon Josefsson.  License: GPLv3+.

# Set up a local KDC, configure Dovecot, and then authenticate with
# GSS-API to the server using 'gsasl' as the client.

set -x

WORKDIR=$(mktemp -d)
cd $WORKDIR

trap 'set +e; kill `cat k/pid`; dovecot -c d/dovecot.conf stop; tail -v -n +0 dovecot.log kdc.log; rm -rf $WORKDIR' 0 INT QUIT ABRT PIPE TERM

set -e

mkdir k
cat<<EOF > k/kdc.conf
[realms]
    GSASL.EXAMPLE = {
        database_name = k/principal
        key_stash_file = k/stash
        kdc_ports = 7500
        kdc_tcp_ports = 7500
        max_life = 10h 0m 0s
        max_renewable_life = 7d 0h 0m 0s
        master_key_type = des3-hmac-sha1
        #supported_enctypes = des3-hmac-sha1
        default_principal_flags = +preauth
    }
[logging]
   kdc = FILE:kdc.log
EOF

cat<<EOF > k/krb5.conf
[libdefaults]
	default_realm = GSASL.EXAMPLE

[domain_realm]
	.`hostname -d` = GSASL.EXAMPLE

[realms]
	GSASL.EXAMPLE = {
		kdc = `hostname -f`:7500
	}
EOF

mkdir d
cat <<EOF > d/dovecot.conf
protocols = imap

auth_gssapi_hostname = `hostname -f`

auth_krb5_keytab = d/dovecot.keytab

auth_verbose=yes
auth_debug=yes

disable_plaintext_auth=no
auth_mechanisms = gssapi
base_dir = .

passdb {
  driver = static
  args = password=pencil
}

userdb {
  driver = static
  args = uid=$USER gid=$USER home=`pwd` mail=mbox:foo
}

# https://wiki.dovecot.org/HowTo/Rootless

default_internal_user = $USER
default_login_user = $USER
default_internal_group = $USER

service anvil {
  chroot =
}
service imap-login {
  chroot =
}
service pop3-login {
  chroot =
}

service imap-login {
  inet_listener imap {
    port = 10143
  }
  inet_listener imaps {
    port = 10993
  }
}

log_path = dovecot.log
EOF

export KRB5_CONFIG=k/krb5.conf
export KRB5_KDC_PROFILE=k
export PATH=$PATH:/usr/sbin

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

#killall krb5kdc dovecot || true

krb5kdc -n -P k/pid &
dovecot -c d/dovecot.conf

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

echo bar | kinit $USER

valgrind --error-exitcode=1 gsasl -m GSSAPI -d --no-starttls --imap `hostname -f` 10143 2>&1 | tee /dev/stderr | grep 'OK Logged in'

exit 0
