#!/bin/sh
##
##  kerberos-setup -- Kerberos database setup procedure
##

if [ $# -ne 2 ]; then
    echo "USAGE: $0 <realm> <domain>"
    echo "EXAMPLE: $0 EXAMPLE.COM example.com"
    exit 1
fi

realm=`echo "$1"  | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
domain=`echo "$2" | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
host=`@l_prefix@/lib/openpkg/shtool echo -e "%h.$domain"`

echo "++ configure Kerberos realm \"$realm\""
sed <@l_prefix@/etc/kerberos/kdc.conf \
    >@l_prefix@/etc/kerberos/kdc.conf.new \
    -e "s;EXAMPLE\.COM;$realm;g" \
    -e "s;example\.com;$domain;g"
cp -p @l_prefix@/etc/kerberos/kdc.conf.new @l_prefix@/etc/kerberos/kdc.conf
rm -f @l_prefix@/etc/kerberos/kdc.conf.new
sed <@l_prefix@/etc/kerberos/krb5.conf \
    >@l_prefix@/etc/kerberos/krb5.conf.new \
    -e "s;kerberos1\.example\.com;$host;" \
    -e "s;kerberos2\.example\.com;$host;" \
    -e "s;EXAMPLE\.COM;$realm;g" \
    -e "s;example\.com;$domain;g"
cp -p @l_prefix@/etc/kerberos/krb5.conf.new @l_prefix@/etc/kerberos/krb5.conf
rm -f @l_prefix@/etc/kerberos/krb5.conf.new

echo "++ initialize Kerberos database"
@l_prefix@/sbin/kdb5_util create -r "$realm" -s

echo "++ adding administrator \"admin@$realm\" to the ACL"
echo "*/admin@$realm *" >@l_prefix@/var/kerberos/db/kadm5.acl
chmod 600 @l_prefix@/var/kerberos/db/kadm5.acl

echo "++ adding administrator \"admin@$realm\" to the Kerberos database"
@l_prefix@/sbin/kadmin.local -p admin/admin -q \
    "addprinc admin/admin@$realm"

echo "++ adding kadmind keytab file to the Kerberos database"
@l_prefix@/sbin/kadmin.local -p admin/admin -q \
    "ktadd -k @l_prefix@/var/kerberos/db/kadm5.keytab kadmin/admin kadmin/changepw"

echo "++ adding local host \"host/$host\" to the Kerberos database"
@l_prefix@/sbin/kadmin.local -p admin/admin -q \
    "addprinc host/$host"

echo "++ creating keytab file for local host \"host/$host\""
@l_prefix@/sbin/kadmin.local -p admin/admin -q \
    "ktadd host/$host"

