# Copyright 2018 Canonical Ltd.
# This code is licensed under the same terms as MIT Kerberos.

set -e

adjust_hostname() {
    local myhostname="$1"

    echo "${myhostname}" > /etc/hostname
    hostname "${myhostname}"
    if ! grep -qE "${myhostname}" /etc/hosts; then
        # just so it's resolvable
        echo "127.0.1.10 ${myhostname}" >> /etc/hosts
    fi
}

create_realm() {
    local realm_name="$1"
    local kerberos_server="$2"

    # start fresh
    rm -rf /var/lib/krb5kdc/*
    rm -rf /etc/krb5kdc/*
    rm -f /etc/krb5.keytab

    # setup some defaults
    cat > /etc/krb5kdc/kdc.conf <<EOF
[kdcdefaults]
    kdc_ports = 750,88
[realms]
    ${realm_name} = {
	    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
	    default_principal_flags = +preauth
    }
EOF

    cat > /etc/krb5.conf <<EOF
[libdefaults]
    default_realm = ${realm_name}
    rdns = false

[realms]
	${realm_name} = {
		kdc = ${kerberos_server}
		admin_server = ${kerberos_server}
	}
EOF
    echo "# */admin *" > /etc/krb5kdc/kadm5.acl

    # create the realm
    kdb5_util create -s -P secretpassword

    # restart services
    systemctl restart krb5-kdc.service krb5-admin-server.service
}

run_test() {
    local testfunc="${1}"
    local -i result=0
    shift
    echo "## TEST ${testfunc}"
    "${testfunc}" "${@}" || result=$?
    if [ ${result} -ne 0 ]; then
        echo "## FAIL ${testfunc}"
    else
        echo "## PASS ${testfunc}"
    fi
    echo
    return ${result}
}
