#!/bin/sh
# Generate a self-signed TLS certificate.  Called from confd keystore
# on first boot (or factory reset) when the gencert entry has empty
# keys.  Output is written to a temporary directory that confd reads
# and then removes after importing into the keystore.

TMPDIR=/tmp/ssl
KEY=$TMPDIR/self-signed.key
CRT=$TMPDIR/self-signed.crt

country=US
state=California
city=Berkeley
org="Acme, Inc."
unit=Second

if [ -f /etc/mkcert.conf ]; then
     . /etc/mkcert.conf
fi

if [ -z "$cn" ]; then
    cn=$1
    if [ -z "$cn" ]; then
	cn=$(hostname).local
    fi
fi

mkdir -p "$TMPDIR"
chmod 700 "$TMPDIR"

gencert --country "$country" --state "$state" --city "$city" --organisation "$org" \
	--organisation-unit "$unit" --common-name "$cn" \
	--out-certificate "$CRT" --out-key "$KEY"

exit $?
