#!/bin/bash
# dlitz 2026
set -eu

EVENT_NAME="$1"
[ "$EVENT_NAME" = "live-updated" ] || exit 42

[ -e "/etc/default/acme-mtik-cert-pusher-hook" ] && . /etc/default/acme-mtik-cert-pusher-hook
[ -e "/etc/conf.d/acme-mtik-cert-pusher-hook" ] && . /etc/conf.d/acme-mtik-cert-pusher-hook
[ -z "${ACME_STATE_DIR-}" ] && ACME_STATE_DIR="/var/lib/acme"

declare -A match_hosts=()
while read name dummy; do
    if [[ "$name" == \#* ]]; then
        # Ignore comments
        continue
    fi
    match_hosts["$name"]=1
done < "$ACME_STATE_DIR/conf/mtik-hosts"

cd /opt/mtik-cert-pusher

while read name; do
    certdir="$ACME_STATE_DIR/live/$name"
    if [ -z "$name" -o ! -e "$certdir" ]; then
        continue
    fi

    if ! [ "${match_hosts[$name]+1}" ]; then
        continue
    fi

    python3 -m mtik_cert_pusher deploy --private-key "$certdir/privkey" --cert "$certdir/cert" --chain "$certdir/chain" --ssh-host "$name"
done
