#!/bin/sh
##
##  milter-dkim-genkey.sh -- DKIM key generation
##

#   command line parsing
if [ $# -eq 0 ]; then
    echo "USAGE: milter-dkim-genkey <selector> [<domain> [<keyfile> [<keysize>]]]" 1>&2
    exit 1
fi
selector="$1"
domain="$2"
keyfile="$3"
keysize="$4"
case "$selector" in
    *.* )
        domain=`echo "$selector" | sed -e 's;^[^.]*\.;;'`
        selector=`echo "$selector" | sed -e 's;^\([^.]*\)\..*$;\1;'`
        ;;
esac
if [ ".$domain" = . ]; then
    domain="`@l_prefix@/lib/openpkg/shtool echo -e '%d' | sed -e 's;^\.;;'`"
fi
if [ ".$keyfile" = . ]; then
    keyfile="@l_prefix@/etc/milter-dkim/$selector.$domain.pem"
fi
if [ ".$keysize" = . ]; then
    keysize="1024"
fi

#   key generation   
echo "++ generating $keysize bit RSA key $keyfile"
if [ ! -f $keyfile ]; then
    (umask 027; @l_prefix@/bin/openssl genrsa -out $keyfile $keysize)
    chown @l_rusr@:@l_musr@ $keyfile; chmod 640 $keyfile
else
    echo "** FILE ALREADY EXISTS, NOT OVERRIDDEN, KEPT AS IS"
fi
echo ""

#   DNS zone record generation   
echo "++ corresponding DNS record (public key part)"
echo "-- [manually place into your DNS zonefile]"
txt=`@l_prefix@/bin/openssl rsa -in $keyfile -pubout -outform PEM |\
     perl -e '$_ = join("", <STDIN>); s/^-----.+?$//mg; s/\n+//sg; printf("t=y; k=rsa; p=%s\n", $_);'`
echo "$selector._domainkey.$domain IN TXT \"$txt\""
echo "_policy._domainkey.$domain IN TXT \"t=y; o=~\""
echo ""

#   OpenPKG run-command configuration generation   
echo "++ corresponding OpenPKG milter-dkim configuration"
echo "-- [manually place into @l_prefix@/etc/rc.conf]"
echo "milter_dkim_selector=\"$selector\""
echo "milter_dkim_domain=\"$domain\""
echo "milter_dkim_keyfile=\"$keyfile\""
echo ""

