#!/usr/bin/env bash
# print-server — part of the unit software (device/system in the source).
#
# The one place a certificate is installed. Nothing is installed unless
# the pair is valid, current, and names this unit.
#
# Two callers:
#   - The gateway's ACME client (the estate's cert-deploy pattern): it
#     uploads fullchain.pem and key.pem by SFTP to the staging directory as
#     acme-deploy, then runs `sudo /usr/local/bin/deploy-print-server-cert.sh`
#     over SSH. sudo clears the environment, so that caller always gets the
#     defaults below.
#   - The unit's own root helper, for a certificate installed by hand
#     (`python3 -m psd cert-helper`): it sets PS_CERT_STAGING to a directory
#     of its own and PS_CERT_SOURCE to manual, or to delivered for one that
#     came through the API.
set -euo pipefail

STAGING="${PS_CERT_STAGING:-/var/lib/acme-deploy/staging}"
SOURCE="${PS_CERT_SOURCE:-acme}"
TLS="${PS_CERT_TLS:-/etc/print-server/tls}"
BACKUP="$TLS/backup"
KEEP=5

log() { echo "$*"; logger -t print-server-cert -- "$*"; }
fail() { log "FAIL: $*"; exit 1; }

case "$SOURCE" in
    acme|manual|delivered) ;;
    *) fail "unknown source '$SOURCE'" ;;
esac

cleanup() { find "$STAGING" -mindepth 1 -delete 2>/dev/null || true; }
trap cleanup EXIT

[ -s "$STAGING/fullchain.pem" ] || fail "missing $STAGING/fullchain.pem"
[ -s "$STAGING/key.pem" ] || fail "missing $STAGING/key.pem"

openssl x509 -noout -in "$STAGING/fullchain.pem" 2>/dev/null || fail "fullchain.pem is not a certificate"
cert_pub=$(openssl x509 -noout -pubkey -in "$STAGING/fullchain.pem" | openssl sha256)
key_pub=$(openssl pkey -pubout -in "$STAGING/key.pem" 2>/dev/null | openssl sha256) || fail "key.pem is not a private key"
[ "$cert_pub" = "$key_pub" ] || fail "the key does not belong to the certificate"
openssl x509 -noout -checkend 86400 -in "$STAGING/fullchain.pem" >/dev/null || fail "the certificate has run out, or does within a day"

# It must name this unit: its host name, with or without a domain, or one of its addresses.
short=$(hostname)
san=$(openssl x509 -noout -ext subjectAltName -in "$STAGING/fullchain.pem" 2>/dev/null | tr ',' '\n')
names=$(echo "$san" | sed -n 's/^ *DNS://p')
addresses=$(echo "$san" | sed -n 's/^ *IP Address://p')
mine=no
for name in $names; do
    case "$name" in
        "$short"|"$short".*) mine=yes ;;
    esac
done
for address in $addresses; do
    for own in $(hostname -I); do
        if [ "$address" = "$own" ]; then mine=yes; fi
    done
done
[ "$mine" = yes ] || fail "the certificate is for [$(echo $names $addresses)], not for $short"

if [ -s "$TLS/cert.pem" ] && cmp -s "$STAGING/fullchain.pem" "$TLS/cert.pem" && [ "$(cat "$TLS/source" 2>/dev/null)" = "$SOURCE" ]; then
    log "that certificate is already installed; nothing to do"
    exit 0
fi

install -d -m 0755 "$TLS"
install -d -m 0700 "$BACKUP"
stamp=$(date +%Y%m%d-%H%M%S)
was=$(cat "$TLS/source" 2>/dev/null || echo self)
if [ -s "$TLS/cert.pem" ] && [ -s "$TLS/key.pem" ]; then
    cp -p "$TLS/cert.pem" "$BACKUP/cert-$stamp.pem"
    cp -p "$TLS/key.pem" "$BACKUP/key-$stamp.pem"
fi

install -m 0600 "$STAGING/key.pem" "$TLS/key.pem.new"
install -m 0644 "$STAGING/fullchain.pem" "$TLS/cert.pem.new"
mv "$TLS/key.pem.new" "$TLS/key.pem"
mv "$TLS/cert.pem.new" "$TLS/cert.pem"
echo "$SOURCE" > "$TLS/source"

if ! nginx -t 2>/dev/null; then
    # Put the previous pair back rather than leave nginx unable to restart.
    if [ -s "$BACKUP/cert-$stamp.pem" ]; then
        cp -p "$BACKUP/cert-$stamp.pem" "$TLS/cert.pem"
        cp -p "$BACKUP/key-$stamp.pem" "$TLS/key.pem"
        echo "$was" > "$TLS/source"
    fi
    fail "nginx refused the new certificate; the previous one is back in place"
fi
systemctl reload nginx

{ ls -1t "$BACKUP"/cert-*.pem 2>/dev/null || true; } | tail -n +$((KEEP + 1)) | xargs -r rm -f
{ ls -1t "$BACKUP"/key-*.pem 2>/dev/null || true; } | tail -n +$((KEEP + 1)) | xargs -r rm -f

log "installed: $(openssl x509 -noout -subject -enddate -in "$TLS/cert.pem" | tr '\n' ' ')"
