#!/bin/sh

# Take the correct binary to create the certificates
CERTTOOL=$(which gnutls-certtool || which certtool)
if [ -z "$CERTTOOL" ]
then
  echo "ERROR: No certtool found" >&2
  exit 1
fi

. ./vars

DNSNAMES="`hostname`"
IPADDRS=$(for ip in $(ifconfig -a | awk '/inet/ {print $2}' | egrep -v '(^::1$|^fe80:|^127\.)') ; do
  if [ -n "$ip" ]
  then
    echo "$ip "
  fi
done)

# Create a server key.
$CERTTOOL \
  --generate-privkey \
  --bits $BITS \
  --outfile server.key.pem

chmod 600 server.key.pem

cat <<EOF >server.info
organization = $ORGANIZATION
cn = $CN
tls_www_server
encryption_key
signing_key
EOF

$CERTTOOL \
  --generate-certificate \
  --load-privkey server.key.pem \
  --load-ca-certificate ca.cert.pem \
  --load-ca-privkey ca.key.pem \
  --template server.info \
  --outfile server.cert.pem

chmod 600 server.cert.pem
rm server.info
exit 0

