#!/bin/bash
# print-server — part of the unit software (device/system in the source).
# Makes this unit's own TLS certificate and key if there is none, or if
# the one it has runs out within 30 days, or names a
# host name or address the unit no longer has. Made on the unit, so no two
# units share a key and none is in the image (D-05, D-13).
set -euo pipefail

dir="${PS_CERT_TLS:-/etc/print-server/tls}"
# 825 days is the longest that Apple devices accept for a certificate a
# person has chosen to trust.
days="${PS_CERT_DAYS:-825}"

# The names and addresses this unit is reached by.
short=$(hostname)
san="DNS:${short}"
domains=$( { hostname -d 2>/dev/null; nmcli -g IP4.DOMAIN device show 2>/dev/null | tr '|' '\n'; } | tr -d ' ' | grep . | sort -u || true)
name=$short
for domain in $domains; do
    san="${san},DNS:${short}.${domain}"
    name="${short}.${domain}"
done
for ip in $(hostname -I); do
    case "$ip" in
        *:*) ;;
        *) san="${san},IP:${ip}" ;;
    esac
done

source=$(cat "$dir/source" 2>/dev/null || true)
if [ -s "$dir/cert.pem" ] && [ -s "$dir/key.pem" ] && { [ "$source" = acme ] || [ "$source" = manual ] || [ "$source" = delivered ]; }; then
    # Delivered from outside or installed by hand. Never replaced from here.
    if ! openssl x509 -in "$dir/cert.pem" -noout -checkend 0 >/dev/null; then
        echo "WARNING: the installed certificate has run out and nothing has replaced it" >&2
    fi
    exit 0
fi

if [ -s "$dir/cert.pem" ] && [ -s "$dir/key.pem" ]; then
    if [ "$(cat "$dir/names" 2>/dev/null)" != "$san" ]; then
        echo "the unit's name or address changed: making a new one"
    elif openssl x509 -in "$dir/cert.pem" -noout -checkend $((30 * 86400)) >/dev/null; then
        exit 0
    else
        echo "certificate runs out within 30 days: making a new one"
    fi
fi

install -d -m 0755 "$dir"      # the certificate is public; the key inside is root's alone
umask 077
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
    -days "$days" -subj "/CN=${name}" \
    -addext "subjectAltName=${san}" \
    -addext "keyUsage=critical,digitalSignature" \
    -addext "extendedKeyUsage=serverAuth" \
    -keyout "$dir/key.pem.new" -out "$dir/cert.pem.new" 2>/dev/null
mv "$dir/key.pem.new" "$dir/key.pem"
mv "$dir/cert.pem.new" "$dir/cert.pem"
chmod 0644 "$dir/cert.pem"
echo "$san" > "$dir/names"
echo self > "$dir/source"
echo "new certificate for ${san}"
if systemctl is-active --quiet nginx 2>/dev/null; then
    systemctl reload nginx
fi
