#!/bin/ksh
# This script creates a CA certficate, then a server certificate with that
# CA as the authority.  Browsers will complain about the validity of the
# certificate because it's signed by a bogus CA, but most can be told to
# use it anyway.

cd ~/.config/pianod || exit 1

# Find the correct certtool
TOOL=$(whence -p gnutls-certtool)
[ "$TOOL" = "" ] && TOOL=$(whence -p certtool)
if [ "$TOOL" = "" ]
then
	print "certtool not found."
	exit 1
fi
message=$($TOOL --version)
if [ $? -ne 0 -o $(print -- "$message" | grep -c "bugs@gnutls") -eq 0 ]
then
	print "Not the right certtool?"
	exit 1
fi
print "Using certtool: $TOOL"

# clean up crap from prior runs
rm *.pem

# Cookbooked from 
# http://gnutls.org/manual/html_node/gnutls_002dserv-Invocation.html

HOST="$1"
[ "$HOST" = "" ] && HOST="$(uname -n)"

# Add support for X.509. First we generate a CA (x509-ca.pem, x509-ca-key.pem).
# These files are not used by pianod; only to generate the key & certificate.
$TOOL --generate-privkey > x509-ca-key.pem
echo 'cn = Homemade CA' > ca.tmpl
echo 'ca' >> ca.tmpl
echo 'cert_signing_key' >> ca.tmpl
$TOOL --generate-self-signed --load-privkey x509-ca-key.pem \
  --template ca.tmpl --outfile x509-ca.pem || exit $?
rm ca.tmpl

# Generate a server certificate with the CA certificate we just generated.
# x509-server.pem & x509-server-key.pem are needed by pianod for HTTPS.
$TOOL --generate-privkey > x509-server-key.pem
echo 'organization = Organization of Chaos' > server.tmpl
echo "cn = $HOST" >> server.tmpl
echo 'tls_www_server' >> server.tmpl
echo 'encryption_key' >> server.tmpl
echo 'signing_key' >> server.tmpl
echo "dns_name = $HOST" >> server.tmpl
$TOOL --generate-certificate --load-privkey x509-server-key.pem \
  --load-ca-certificate x509-ca.pem --load-ca-privkey x509-ca-key.pem \
  --template server.tmpl --outfile x509-server.pem || exit $?
rm server.tmpl

