#!/bin/sh
set -e

BEFORE_RULES=/etc/ufw/before.rules

# Remove the rule blocks this package inserted, together with the single blank
# line that precedes each one, so before.rules returns to its original content.
strip_ufw_blocks() {
    [ -f "$BEFORE_RULES" ] || return 0
    grep -q '^# ROUTER MSS RULES START$\|^# IPSEC RULES START$' "$BEFORE_RULES" || return 0

    tmp="$(mktemp)"
    awk '
        /^# (IPSEC|WIREGUARD|OPENVPN|P2S DNS|WEB|BOOTSTRAP|MANAGER|HTTPS|METRICS|SITES|DNS|ROUTER FORWARD|ROUTER NAT|ROUTER MSS) RULES START$/ {
            skip = 1; pending = 0; next
        }
        /^# (IPSEC|WIREGUARD|OPENVPN|P2S DNS|WEB|BOOTSTRAP|MANAGER|HTTPS|METRICS|SITES|DNS|ROUTER FORWARD|ROUTER NAT|ROUTER MSS) RULES END$/ {
            skip = 0; next
        }
        skip { next }
        /^$/ { pending++; next }
        {
            while (pending > 0) { print ""; pending-- }
            print
        }
        END { while (pending > 0) { print ""; pending-- } }
    ' "$BEFORE_RULES" > "$tmp"

    cat "$tmp" > "$BEFORE_RULES"
    rm -f "$tmp"
}

case "$1" in
    purge)
        strip_ufw_blocks

        # Let ucf forget the file before it is removed, or a reinstall finds a
        # stale hash and declines to lay the file down again.
        if command -v ucf >/dev/null 2>&1; then
            ucf --purge /etc/vpn-router/vpn-router.json
        fi
        if command -v ucfr >/dev/null 2>&1; then
            ucfr --purge vpn-router /etc/vpn-router/vpn-router.json
        fi

        rm -f /etc/swanctl/conf.d/site-to-site.conf \
              /etc/swanctl/conf.d/road-warrior.conf \
              /etc/systemd/resolved.conf.d/p2s-forwarder.conf \
              /etc/wireguard/wg0.conf \
              /etc/openvpn/server/vpn-router.conf \
              /etc/openvpn/server/vpn-router-ldap.conf \
              /etc/caddy/vpn-router.Caddyfile \
              /etc/powerdns/pdns.d/vpn-router.conf \
              /etc/vpn-router/vpn-router.json \
              /etc/vpn-router/web.key \
              /etc/vpn-router/oidc.key \
              /etc/vpn-router/metrics.secret \
              /etc/systemd/system/vpn-router-backup.timer.d/schedule.conf \
              /etc/sudoers.d/vpn-router \
              /etc/ssh/sshd_config.d/vpn-router.conf \
              /var/lib/vpn-router/setup.done \
              /var/lib/vpn-router/backup.json
        rmdir --ignore-fail-on-non-empty /etc/systemd/system/vpn-router-backup.timer.d 2>/dev/null || true
        # The name service no longer looks up the console accounts of the router's directory.
        sed -i '/^passwd:/s/ ldap\b//' /etc/nsswitch.conf
        rm -rf /var/lib/vpn-router/backup/staging /var/lib/vpn-router/backup/restore \
               /var/lib/vpn-router/pki-publish /etc/caddy/vpn-router-pki /etc/caddy/vpn-router-sites \
               /etc/openvpn/server/vpn-router-ca.pem /etc/openvpn/server/vpn-router-crl.pem
        rmdir --ignore-fail-on-non-empty /var/lib/vpn-router/backup /var/lib/vpn-router 2>/dev/null || true

        # The refresh tokens' database and role, when the package created them.
        if [ -f /etc/vpn-router/database.secret ] && command -v psql >/dev/null 2>&1; then
            runuser -u postgres -- psql -X -q -c 'DROP DATABASE IF EXISTS "vpn-router"' || true
            runuser -u postgres -- psql -X -q -c 'DROP ROLE IF EXISTS "vpn-router"' || true
        fi
        rm -f /etc/vpn-router/database.secret

        # The databases and roles of the web sites and of the name server, when the package created them.
        for database in vpn-router-sites vpn-router-dns; do
            secret="/etc/vpn-router/${database#vpn-router-}-database.secret"
            if [ -f "$secret" ] && command -v psql >/dev/null 2>&1; then
                runuser -u postgres -- psql -X -q -c "DROP DATABASE IF EXISTS \"$database\"" || true
                runuser -u postgres -- psql -X -q -c "DROP ROLE IF EXISTS \"$database\"" || true
            fi
            rm -f "$secret"
        done

        # Key material, users and content are not package state: /etc/vpn-router/pki,
        # /etc/vpn-router/ldap, /etc/vpn-router/rclone.conf, the user directory
        # in slapd, the WireGuard key pair, everything under /etc/swanctl, the
        # files of the web sites in /var/lib/vpn-router/sites, the backups and
        # what a restore replaced are left in place. Caddy, rclone and PowerDNS
        # stay installed, so Caddy's repository, which vpn-router-caddy
        # configures, stays too.
        rmdir --ignore-fail-on-non-empty /etc/vpn-router 2>/dev/null || true
        ;;
esac

#DEBHELPER#
