#!/bin/sh
#
# argos prerm — on removal stop and disable the units and drop the
# console's nginx site.
# An upgrade leaves the units running: postinst restarts them on the new
# payload (the console through console-setup, the WAN monitor directly), so
# failover never waits for a reboot. A deconfigure (a dependency being
# swapped) leaves everything in place too: dpkg configures the package again
# afterwards, and disabled units would boot the appliance without its ruleset.
# IPv4 forwarding goes with the package only when argos turned it on (its
# sysctl drop-in): someone else's forwarding is never touched. The DPI
# engines' units, which argos writes itself, go too: no engine is left
# running unmanaged. Debian's own suricata.service is unmasked when argos is
# the one that masked it (its marker), and left disabled: an appliance is not
# the host that stock unit was written for, and putting its restart loop back
# would be a parting gift nobody wants. systemd's ssh generator is unmasked on
# the same terms — its own marker — so a host that keeps the package's traces
# out of the way gets its stock sshd sockets back with the package gone.
# argos's DHCP (one dnsmasq, its own unit) stops and its config goes; the
# lease file stays with argos's state. A Kea argos ran before 1.2.16 and never
# moved off (its drop-in still there) is stopped the same way; a Kea argos
# never managed is left alone. The Citadel link's units stop and wg-citadel
# goes down, and so do the Atlas link's and wg-atlas; the links' state stays
# for a reinstall. The PPPoE links' pppd stop, and their peer files go.
#
set -e

DENO=/usr/bin/deno
FORWARDING_DROPIN=/etc/sysctl.d/60-argos-forwarding.conf
# The connection table's drop-in and module list (DEFCON.md D4).
CONNTRACK_DROPIN=/etc/sysctl.d/61-argos-conntrack.conf
CONNTRACK_MODULES=/etc/modules-load.d/argos-conntrack.conf
# A publication's SYN proxy: strict TCP tracking and its drop-in (DEFCON.md D2).
SYNPROXY_DROPIN=/etc/sysctl.d/62-argos-synproxy.conf
TCP_LOOSE=/proc/sys/net/netfilter/nf_conntrack_tcp_loose
ENGINE_UNIT_DIR=/etc/systemd/system
STOCK_MASK_MARKER=/var/lib/argos/.suricata-stock-masked
SSH_GENERATOR=/etc/systemd/system-generators/systemd-ssh-generator
SSH_GENERATOR_MARKER=/var/lib/argos/.ssh-generator-masked
KEA_DROPIN=/etc/systemd/system/kea-dhcp4-server.service.d/argos.conf

case "$1" in
  remove|purge)
    if command -v systemctl >/dev/null 2>&1; then
      systemctl disable --now argos.service argos-firewall.service argos-network.service argos-wan-monitor.service argos-tls.timer argos-dns-refresh.timer argos-appid.service argos-appid-update.timer argos-intel.service argos-intel-update.timer argos-intel-watch.timer argos-geo-update.timer argos-decoy.service argos-decoy-watch.timer >/dev/null 2>&1 || true
      # The timers' oneshots have no [Install] section: a pass still running is only stopped.
      systemctl stop argos-tls.service argos-dns-refresh.service argos-appid-update.service argos-intel-update.service argos-intel-watch.service argos-geo-update.service argos-decoy-watch.service >/dev/null 2>&1 || true
      # One by one: either engine may never have been installed. The ruleset
      # timer goes with Suricata, and a download it started is stopped.
      # argos-zeek.service is the single unit of the releases before the
      # template.
      for unit in argos-suricata.service argos-suricata-update.timer argos-zeek.service; do
        systemctl disable --now "$unit" >/dev/null 2>&1 || true
      done
      systemctl stop argos-suricata-update.service >/dev/null 2>&1 || true
      # Zeek is a template, one instance per tapped interface: the running
      # instances are stopped by pattern, and disabling the template takes
      # every instance's link with it.
      systemctl stop 'argos-zeek@*.service' >/dev/null 2>&1 || true
      systemctl disable argos-zeek@.service >/dev/null 2>&1 || true
      if [ -e "$STOCK_MASK_MARKER" ]; then
        systemctl unmask suricata.service >/dev/null 2>&1 || true
        rm -f "$STOCK_MASK_MARKER"
      fi
    fi
    # Application control's address sink: its table refuses traffic nothing
    # would manage any more (the Suricata rules die with the engine's unit).
    if command -v nft >/dev/null 2>&1; then
      nft delete table inet argos_appid >/dev/null 2>&1 || true
      # The threat intelligence's table, for the same reason (its caches stay for a reinstall).
      nft delete table inet argos_intel >/dev/null 2>&1 || true
      # The decoys' quarantine (info/HONEYPOT.md): forward drops nothing would lift any more.
      nft delete table inet argos_decoy >/dev/null 2>&1 || true
    fi
    # The decoys themselves: the namespace takes its ipvlans and rules with it; the kernel's switch for the
    # namespaces' log lines goes back off only when argos switched it on. The contacts stay. Plain sh when the
    # runtime cannot: the namespace at least (the switch and /run go at the next boot).
    "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/decoy-setup.ts remove || \
      ip netns del argos-decoy >/dev/null 2>&1 || true
    # The block page: its service and the dummy interface its address lives on; the authority stays for a reinstall.
    "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/blockpage-setup.ts remove || {
      systemctl disable --now argos-blockpage.service argos-blockpage-signer.service >/dev/null 2>&1 || true
      ip link del argos-block >/dev/null 2>&1 || true
    }
    rm -f "$ENGINE_UNIT_DIR/argos-suricata.service" "$ENGINE_UNIT_DIR/argos-suricata-update.service" "$ENGINE_UNIT_DIR/argos-suricata-update.timer" \
      "$ENGINE_UNIT_DIR/argos-zeek@.service" "$ENGINE_UNIT_DIR/argos-zeek.service"
    # systemd's ssh generator goes back to generating, on argos's marker only:
    # a mask an operator put there himself is not argos's to undo.
    if [ -e "$SSH_GENERATOR_MARKER" ]; then
      if [ "$(readlink "$SSH_GENERATOR" 2>/dev/null || true)" = "/dev/null" ]; then
        rm -f "$SSH_GENERATOR"
      fi
      rm -f "$SSH_GENERATOR_MARKER"
    fi
    if command -v systemctl >/dev/null 2>&1; then
      systemctl daemon-reload >/dev/null 2>&1 || true
    fi
    # The drop-in would switch routing on at the next boot, with no argos
    # filter left to load: it goes, and the switch goes off. After the units
    # stopped, so a pending apply has rolled back first. Plain sh when the
    # embedded runtime cannot do it — in withdrawForwarding's order, the switch
    # first and the drop-in (the record that the forwarding is argos's) last,
    # but each tried whatever the other did: with the package gone there is no
    # later try, and either one left behind routes with no argos filter.
    if ! "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/forwarding-remove.ts; then
      if [ -e "$FORWARDING_DROPIN" ]; then
        echo 0 2>/dev/null >/proc/sys/net/ipv4/ip_forward || echo "argos: WARNING — IPv4 forwarding is still on (sysctl -w net.ipv4.ip_forward=0)" >&2
        rm -f "$FORWARDING_DROPIN" || echo "argos: WARNING — $FORWARDING_DROPIN could not be removed: the next boot routes with no argos filter" >&2
      fi
    fi
    # The connection table's drop-in (DEFCON.md D4) goes with the package; an
    # operator's own file stays. Plain rm by its marker when the runtime cannot.
    if ! ARGOS_SYSCTL_CONNTRACK="$CONNTRACK_DROPIN" ARGOS_MODULES_LOAD_CONNTRACK="$CONNTRACK_MODULES" "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/conntrack-setup.ts remove; then
      if head -n 1 "$CONNTRACK_DROPIN" 2>/dev/null | grep -q "^# Managed by EDON Argos"; then rm -f "$CONNTRACK_DROPIN"; fi
      rm -f "$CONNTRACK_MODULES"
    fi
    # The SYN proxies go with the package: TCP tracking back to the kernel's default, argos's drop-in removed.
    if [ -e "$SYNPROXY_DROPIN" ]; then
      echo 1 2>/dev/null >"$TCP_LOOSE" || true
      rm -f "$SYNPROXY_DROPIN"
    fi
    # The WAF goes with the package (info/WAF.md): the proxies' site again without the glue, AppSec's files removed
    # (CrowdSec reloaded), the WAF's nginx file removed; the proxies stay served. Plain rm when the runtime cannot: the
    # glue left in the site calls nothing (it loads through pcall) and lets every request through.
    "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/waf-setup.ts remove || \
      rm -f /etc/nginx/conf.d/argos-waf.conf
    rm -f /etc/nginx/conf.d/argos.conf
    if command -v systemctl >/dev/null 2>&1; then
      systemctl reload nginx.service >/dev/null 2>&1 || true
    fi
    # The IPsec tunnels go with the package: argos's connections taken down,
    # its swanctl file removed (it holds the pre-shared keys), its XFRM
    # interfaces deleted. strongSwan itself stays installed.
    "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/ipsec-setup.ts remove || \
      rm -f /etc/swanctl/conf.d/argos.conf
    # The OpenVPN tunnels go with the package: every instance stopped (its
    # template goes too), argos's configs removed. The credentials under
    # /etc/edon/openvpn stay with argos's settings: a reinstall finds them, and
    # the boot pass (argos-network.service) brings the tunnels back. The
    # instances' wants links go by hand: disabling the template leaves them.
    "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/openvpn-setup.ts remove || true
    if command -v systemctl >/dev/null 2>&1; then
      systemctl stop 'argos-openvpn@*.service' >/dev/null 2>&1 || true
      systemctl disable argos-openvpn@.service >/dev/null 2>&1 || true
    fi
    rm -f /etc/systemd/system/multi-user.target.wants/argos-openvpn@*.service
    rm -rf /etc/openvpn/argos
    # A Kea argos set up before 1.2.16 and never moved off (its drop-in on
    # Debian's kea unit) stops with the package: nothing would keep its config in
    # line with the interfaces any more. A Kea argos never managed is not touched.
    if [ -e "$KEA_DROPIN" ]; then
      if command -v systemctl >/dev/null 2>&1; then
        systemctl disable --now kea-dhcp4-server.service >/dev/null 2>&1 || true
      fi
      rm -f "$KEA_DROPIN" /etc/kea/argos/kea-dhcp4.conf /etc/kea/argos-dhcp4.conf
      rmdir /etc/kea/argos 2>/dev/null || true
      rmdir "$(dirname "$KEA_DROPIN")" 2>/dev/null || true
      if command -v systemctl >/dev/null 2>&1; then
        systemctl daemon-reload >/dev/null 2>&1 || true
      fi
    fi
    # argos's DHCP: its unit (and the relay-only one of 1.2.14–1.2.15, should a
    # host still have it), the configs beside argos.json.
    if command -v systemctl >/dev/null 2>&1; then
      systemctl disable --now argos-dhcp.service >/dev/null 2>&1 || true
      systemctl disable --now argos-dhcp-relay.service >/dev/null 2>&1 || true
    fi
    rm -f /etc/edon/argos-dhcp.conf /etc/edon/argos-dhcp-relay.conf
    # The Citadel link: its timer, its TCP relay and wg-citadel stop, and
    # wg-citadel's configuration (it holds the link's private key) goes. The
    # link's state stays with argos's settings: a reinstall puts it back up.
    if ! "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/citadel-link.ts remove; then
      if command -v systemctl >/dev/null 2>&1; then
        systemctl disable --now argos-citadel-link.timer >/dev/null 2>&1 || true
        systemctl stop argos-citadel-link.service argos-citadel-tunnel.service >/dev/null 2>&1 || true
        systemctl disable --now wg-quick@wg-citadel.service >/dev/null 2>&1 || true
      fi
      rm -f /etc/wireguard/wg-citadel.conf
    fi
    # The Atlas link: its timer and wg-atlas stop, and wg-atlas's configuration
    # (it holds the site's private key and the PSK) goes. The link's state
    # stays with argos's settings: a reinstall puts it back up.
    if ! "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/atlas-link.ts remove; then
      if command -v systemctl >/dev/null 2>&1; then
        systemctl disable --now argos-atlas-link.timer >/dev/null 2>&1 || true
        systemctl stop argos-atlas-link.service >/dev/null 2>&1 || true
        systemctl disable --now wg-quick@wg-atlas.service >/dev/null 2>&1 || true
      fi
      rm -f /etc/wireguard/wg-atlas.conf
    fi
    # EDON Krios: the timer stops; the registration stays for a reinstall.
    if ! "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/krios-service.ts remove; then
      if command -v systemctl >/dev/null 2>&1; then
        systemctl disable --now argos-krios.timer >/dev/null 2>&1 || true
        systemctl stop argos-krios.service >/dev/null 2>&1 || true
      fi
    fi
    # The backup on Atlas: the agent is its own package and stays enrolled;
    # argos's pre-backup hook goes with argos (plain rm: it is one file).
    rm -f /etc/edon/agent.d/hooks/pre.d/50-argos
    # The PPPoE links: every pppd stops (its template goes with the package),
    # and the files argos wrote for it go — the peer files hold the passwords.
    # The passwords' store stays with argos's settings: a reinstall finds it.
    # The instances' wants links go by hand: disabling the template leaves
    # them. A reinstall enables the links again from argos's settings (the
    # boot pass, argos-network.service, which the postinst starts).
    if command -v systemctl >/dev/null 2>&1; then
      systemctl stop 'argos-pppoe@*.service' >/dev/null 2>&1 || true
      systemctl disable argos-pppoe@.service >/dev/null 2>&1 || true
    fi
    rm -f /etc/systemd/system/multi-user.target.wants/argos-pppoe@*.service
    rm -f /etc/ppp/peers/argos-ppp* /etc/ppp/argos-ppp*.env /etc/ppp/ip-up.d/argos-gateways /etc/ppp/ip-up.d/argos-shaping
    ;;
esac

exit 0
