#!/bin/bash
#
# This script will create an SSL certificate that contains the Bogen Root CA
# and any number of IP addresses supplied on the command line.
#
# $@ = One or more IP addresses/DNS names to include in the SSL cert
#
# (C) Copyright 2020-2022, Bogen Communications LLC. All rights reserved.
#
if [ "$#" -lt 1 ]; then
	IP_ADDR=$(hostname -I)
else
	IP_ADDR=$1
fi

PATH=/bin:/usr/bin:/sbin/:/usr/sbin

CERT_DIR=/opt/bogen/certs
PRIVATE_DIR=/etc/lighttpd/private
SAN_FILE=$PRIVATE_DIR/san.cnf
LIGHTTPD_KEY=$PRIVATE_DIR/lighttpd.key
LIGHTTPD_CRT=$PRIVATE_DIR/lighttpd.crt
LIGHTTPD_PEM=$PRIVATE_DIR/lighttpd.pem
BOGEN_KEY=$PRIVATE_DIR/bogenCA.key
BOGEN_CRT=$PRIVATE_DIR/bogenCA.crt
CSR_FILE=$PRIVATE_DIR/lighttpd.csr
PEM_FILE=$PRIVATE_DIR/bogenCA.pem

# Bail out immediately if any command fails
set -e

# Validate that we have a non-empty IP address before doing anything
if [ -z "$IP_ADDR" ]; then
    echo "ERROR: No IP address provided or detected. Aborting." >&2
    exit 1
fi

sudo cp -vfp $CERT_DIR/* $PRIVATE_DIR 

sed -i "/^IP.1/c\IP.1 = $IP_ADDR" $SAN_FILE
sed -i "/^commonName/c\commonName = $IP_ADDR" $SAN_FILE

#
# Create csr
#
openssl req -new -newkey rsa:2048 -nodes -keyout $LIGHTTPD_KEY -config $SAN_FILE -out $CSR_FILE

#
# Create self signed certificate issued by BogenCA
#
openssl x509 -req -in $CSR_FILE -CA $PEM_FILE -CAkey $BOGEN_KEY -CAcreateserial -out $LIGHTTPD_CRT -days 730 -sha256 -extfile <(printf 'subjectAltName=IP:'$IP_ADDR'') -passin file:"$PRIVATE_DIR/5f4dcc3b5aa765d61d8327deb882cf99"

#
# Validate that both the key and cert files are non-empty before concatenating
#
if [ ! -s "$LIGHTTPD_KEY" ] || [ ! -s "$LIGHTTPD_CRT" ]; then
    echo "ERROR: Key or certificate file is empty after generation. Aborting." >&2
    exit 1
fi

#
# Write to a temp file first, then atomically move it into place so the
# live lighttpd.pem is never left in a partial/empty state
#
LIGHTTPD_PEM_TMP="${LIGHTTPD_PEM}.tmp"
cat $LIGHTTPD_KEY $LIGHTTPD_CRT > $LIGHTTPD_PEM_TMP
mv $LIGHTTPD_PEM_TMP $LIGHTTPD_PEM

#
# Validate the final PEM before deploying it
#
if [ ! -s "$LIGHTTPD_PEM" ]; then
    echo "ERROR: lighttpd.pem is empty after concatenation. Aborting." >&2
    exit 1
fi

#
# copy to certs directory
#
cp $LIGHTTPD_PEM /etc/lighttpd/certs/lighttpd.pem
cp $PEM_FILE /etc/lighttpd/certs/bogenCA.pem

#
# copy bogenCA to public folder
#
cp $BOGEN_CRT /var/www/html/ssl/bogenCA.crt

rm -rf $PRIVATE_DIR/*

systemctl restart lighttpd

exit 0
