#!/bin/sh
##
##  kerberos-setup -- Kerberos 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 @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 @l_prefix@/etc/kerberos/krb5.conf.new @l_prefix@/etc/kerberos/krb5.conf
rm -f @l_prefix@/etc/kerberos/krb5.conf.new

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

echo "++ adding administrator \"admin@$realm\" to Kerberos database"
echo "*/admin@$realm *" >@l_prefix@/var/kerberos/db/$realm.acl
chmod 600 @l_prefix@/var/kerberos/db/$realm.acl
chown @l_susr@:@l_mgrp@ @l_prefix@/var/kerberos/db/$realm.acl
@l_prefix@/sbin/kadmin.local -p admin/admin -q \
    "add_principal -pw admin admin/admin@$realm"
echo "host/$host@$realm" >@l_prefix@/var/kerberos/db/kpropd.acl
chmod 600 @l_prefix@/var/kerberos/db/kpropd.acl
chown @l_susr@:@l_mgrp@ @l_prefix@/var/kerberos/db/kpropd.acl

echo "++ exporting keytab for \"kadmin/admin\" and \"kadmin/changepw\" from Kerberos database"
@l_prefix@/sbin/kadmin.local -p admin/admin -q \
    "ktadd -q -k @l_prefix@/var/kerberos/db/$realm.keytab kadmin/admin kadmin/changepw"

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

echo "++ exporting keytab for \"host/$host\" from Kerberos database"
@l_prefix@/sbin/kadmin.local -p admin/admin -q \
    "ktadd -q -k @l_prefix@/etc/kerberos/krb5.keytab host/$host"

