#!/bin/sh

usage() {
    echo "Usage: $0 [-f] <keybase> <selector> <domain>"
    echo "If KEYBASE/<domain>/<selector> doesn't exist or if option -f is"
    echo "given, a new RSA private key will be generated in that location."
    echo "Then, the private key in that location will be used to generate a"
    echo "public key and a tinydns TXT record for the selector, domain and"
    echo "key will be printed on STDOUT."
    exit $1
}

force=0
if [ "$1" = "-f" ]; then
    force=1
    shift
fi

if [ "$#" -lt 3 ]; then
    usage 1;
fi

KEYBASE="$1"
shift

KEYDIR="$KEYBASE/$2"
if [ ! -d "$KEYDIR" ]; then
    echo "$KEYDIR doesn't exist!"
    exit 1
fi

KEYFILE="$KEYDIR/$1"

if [ "$force" != 0 -o ! -f "$KEYFILE" ]; then
    umask 027
    openssl genrsa -out "$KEYFILE" 1024
fi

echo -n "'$1._domainkey.$2:v=DKIM1; p="
openssl rsa -in "$KEYFILE" -pubout -outform PEM 2>/dev/null | \
  sed '/^---/d;/^writing RSA key/d' | \
  tr -d '\012'
echo

