#!/bin/sh

set -eu

# expected arguments
[ "$1 $2" = "ipa request" ] || exit 1
REALM="$3"
USER="$4"

HOST="$(hostname -f)"
SERVICE="HTTP/${HOST}@${REALM}"
COCKPIT_GROUP="cockpit-ws"

# use a temporary keytab to avoid interfering with the system one
export KRB5CCNAME=/run/cockpit/keytab-setup

# ipa-getkeytab needs root to create the file, same for cert installation
[ $(id -u) = 0 ] || exit 0

# not an IPA setup? cannot handle this
type ipa >/dev/null 2>&1 || exit 0

# IPA operations require auth; read password from stdin to avoid quoting issues
# if kinit fails, we can't handle this setup, exit cleanly
kinit "${USER}@${REALM}" || exit 0

# ensure this gets run with a non-C locale; ipa fails otherwise
if [ $(sh -c 'eval `locale`; echo $LC_CTYPE') = 'C' ]; then
    export LC_CTYPE=C.UTF-8
fi

# create a kerberos Service Principal Name for cockpit-ws, unless already present
ipa service-show "${SERVICE}" || ipa service-add --ok-as-delegate=true --force "${SERVICE}"

# add cockpit-ws key, unless already present
mkdir -p /etc/cockpit
klist -k /etc/cockpit/krb5.keytab | grep -qF "${SERVICE}" || ipa-getkeytab -p "HTTP/${HOST}" -k /etc/cockpit/krb5.keytab

# ipa-getcert cannot set permisisons nor write into /etc/cockpit due to SELinux
if ipa-getcert request -f /run/cockpit/ipa.crt -k /run/cockpit/ipa.key -K "HTTP/${HOST}" -w -v; then
    mv -Z /run/cockpit/ipa.crt /etc/cockpit/ws-certs.d/10-ipa.cert
    mv -Z /run/cockpit/ipa.key /etc/cockpit/ws-certs.d/10-ipa.key

    # The certificate should be world-readable
    chmod a+r /etc/cockpit/ws-certs.d/10-ipa.cert

    # If COCKPIT_GROUP is set, then make sure the key is readable by that group too
    if [ -n "${COCKPIT_GROUP}" ]; then
        chown root:"${COCKPIT_GROUP}" /etc/cockpit/ws-certs.d/10-ipa.key
        chmod g+r /etc/cockpit/ws-certs.d/10-ipa.key
    fi
fi
