#!/bin/sh
set -e
TOOLS="edns:easydns ed:easydig eh:easyhost ens:easynslookup etrace:easytrace ednssec:easydnssec eptr:easyptr ezone:easyzone econf:easyconf ebench:easybench ewhois:easywhois edoh:easydoh edot:easydot ediff:easydiff"
if [ "$1" = "configure" ]; then
    if ! getent passwd easydns >/dev/null; then
        adduser --system --group --home /etc/easydns/data --no-create-home --shell /usr/sbin/nologin easydns >/dev/null
    fi
    # /etc/easydns: config, zones.d/, keys.d/ (root:easydns, not world-readable – may hold keys)
    install -d -o root -g easydns -m 0750 /etc/easydns /etc/easydns/zones.d /etc/easydns/keys.d
    # data_dir: zones/primary/ (your zone files), zones/secondary/ (transferred copies),
    # zones/signed/ (DNSSEC), journals, control token
    install -d -o easydns -g easydns -m 0750 /etc/easydns/data /etc/easydns/data/zones \
        /etc/easydns/data/zones/primary /etc/easydns/data/zones/secondary
    chgrp easydns /etc/easydns/config.yaml 2>/dev/null || true
    chmod 0640 /etc/easydns/config.yaml 2>/dev/null || true
    # Short tool names only when the name is free (e.g. `ed` is often the line editor).
    for pair in $TOOLS; do
        s="${pair%%:*}"; l="${pair##*:}"
        if [ ! -e "/usr/bin/$s" ] && ! command -v "$s" >/dev/null 2>&1; then
            ln -s "$l" "/usr/bin/$s"
        fi
    done
    if [ -d /run/systemd/system ]; then
        systemctl daemon-reload >/dev/null || true
        if [ -n "$2" ] && systemctl is-active --quiet easydns.service; then
            # Upgrade of a running server: restart only if the new version accepts the
            # configuration (checked as the service user); otherwise keep the old one running.
            if command -v runuser >/dev/null 2>&1; then
                CHECK="runuser -u easydns -- /usr/bin/easydns check-config --config /etc/easydns/config.yaml"
            else
                CHECK="/usr/bin/easydns check-config --config /etc/easydns/config.yaml"
            fi
            if $CHECK >/tmp/easydns-upgrade-check.log 2>&1; then
                systemctl restart easydns.service && echo "EasyDNS upgraded from $2 and restarted."
                rm -f /tmp/easydns-upgrade-check.log
            else
                echo "WARNING: the new EasyDNS rejects /etc/easydns/config.yaml; the previous version keeps running."
                echo "  details: /tmp/easydns-upgrade-check.log   fix, then: systemctl restart easydns"
            fi
        elif [ -z "$2" ]; then
            echo "EasyDNS installed (hybrid: authoritative + recursive for LAN)."
            echo "  config: /etc/easydns/config.yaml   zones: /etc/easydns/data/zones/primary/"
            echo "  new zone: easydns zone create example.com --ns ns1.example.com --ip 192.0.2.1"
            echo "  start:    systemctl enable --now easydns   then: easydns status"
        fi
    fi
fi
exit 0
