#!/bin/sh
#
# argos postinst — register the units and put the console behind nginx. Every
# unit and script runs on edon-deno's /usr/bin/deno, the pinned Deno of the
# EDON appliances (a dependency of the package).
#
set -e

DENO=/usr/bin/deno

# dpkg's trigger on /usr/bin/crowdsec (scripts/DEBIAN/triggers): CrowdSec upgraded without argos — an unattended upgrade
# that took the official package from the EDON repository. Only CrowdSec's repair and switch (issue #12): the rest of
# this script is an install's, not a trigger's.
if [ "$1" = triggered ]; then
  "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/crowdsec-engine.ts triggered || \
    echo "argos: WARNING — CrowdSec was not checked after its upgrade (the console tries again within the hour)" >&2
  exit 0
fi

# A direct-mode drop-in of an earlier release (the nginx front was down: HOST=0.0.0.0 PORT=<n> ARGOS_CONSOLE_DIRECT=1, no ARGOS_DIRECT_PORT) runs
# this release's app on a public port with no front to name its clients: the zone gate would place every one of them as the box itself.
# Rewritten first of all, before anything can start the app, to the direct front (scripts/direct-console.ts) on the same port;
# console-setup.ts later replaces it altogether once the nginx front is up.
DIRECT_DROPIN=/etc/systemd/system/argos.service.d/argos-direct.conf
if [ -f "$DIRECT_DROPIN" ] && grep -q 'ARGOS_CONSOLE_DIRECT=1' "$DIRECT_DROPIN" && ! grep -q 'ARGOS_DIRECT_PORT=' "$DIRECT_DROPIN"; then
  DIRECT_PORT=$(sed -n 's/^Environment=PORT=\([0-9][0-9]*\)$/\1/p' "$DIRECT_DROPIN" | head -n 1)
  [ -n "$DIRECT_PORT" ] || DIRECT_PORT=8000
  printf '%s\n' '# Written by EDON Argos: the nginx front is down, the console answers here directly.' '# scripts/console-setup.ts removes it once the front is up.' '[Service]' "Environment=ARGOS_DIRECT_PORT=$DIRECT_PORT" 'Environment=ARGOS_CONSOLE_DIRECT=1' 'ExecStart=' 'ExecStart=/usr/bin/deno run -A --node-modules-dir=manual /usr/lib/argos/scripts/direct-console.ts' > "$DIRECT_DROPIN.new" && mv "$DIRECT_DROPIN.new" "$DIRECT_DROPIN"
  echo "argos: the direct-mode drop-in now runs the direct front on port $DIRECT_PORT"
fi

# certbot replays the hooks it stored at issuance (tls.server hookCommand: the
# console's open/close/deployed, the reverse proxies' deploy hook), and those
# name the Deno argos ran on then. Up to 1.2.15 that was argos's own copy,
# /usr/lib/argos/deno/deno, which is gone: left as it was, every certificate
# would fail its next renewal ("Unable to find pre-hook command"). The stored
# hooks follow edon-deno's binary instead; a renewal file argos did not write
# carries no such path and is left as it is.
LE_RENEWAL=/etc/letsencrypt/renewal
for conf in "$LE_RENEWAL"/*.conf; do
  [ -f "$conf" ] || continue
  if grep -q '/usr/lib/argos/deno/deno ' "$conf"; then
    sed -i 's#/usr/lib/argos/deno/deno #/usr/bin/deno #g' "$conf"
    echo "argos: $conf now replays its hooks on /usr/bin/deno"
  fi
done

# Let's Encrypt http-01 webroot served by the console's nginx site: nginx's
# workers must traverse it whatever umask dpkg was started with.
install -d -m 0755 /var/lib/argos /var/lib/argos/acme

# systemd's own ssh generator binds a socket-activated sshd to AF_VSOCK — the
# hypervisor's channel into the guest, which no zone in Settings governs — and
# to a local AF_UNIX socket, at every boot and every daemon-reload. On a
# virtualised appliance with no vsock device attached it also fails the CID
# query each time it runs ("Failed to query local AF_VSOCK CID: Cannot assign
# requested address", priority err), in the log page an operator opens to find
# the appliance's own errors. It is masked the way systemd masks a generator,
# once and on a marker: an override an operator wrote himself is never touched,
# and neither is an unmask he decides on later.
SSH_GENERATOR=/etc/systemd/system-generators/systemd-ssh-generator
SSH_GENERATOR_MARKER=/var/lib/argos/.ssh-generator-masked
if [ ! -e "$SSH_GENERATOR_MARKER" ] && [ ! -e "$SSH_GENERATOR" ] && [ ! -L "$SSH_GENERATOR" ]; then
  if install -d -m 0755 "${SSH_GENERATOR%/*}" && ln -sfn /dev/null "$SSH_GENERATOR"; then
    touch "$SSH_GENERATOR_MARKER"
    # The reload below drops the generated units, but a unit that is already
    # listening stays up as one systemd no longer has a file for: stopped here,
    # while it still is one.
    if command -v systemctl >/dev/null 2>&1; then
      systemctl stop sshd-vsock.socket sshd-unix-local.socket >/dev/null 2>&1 || true
    fi
  else
    echo "argos: WARNING — systemd's ssh generator could not be masked ($SSH_GENERATOR): a virtualised appliance keeps logging 'Failed to query local AF_VSOCK CID' at every daemon-reload" >&2
  fi
fi

if command -v systemctl >/dev/null 2>&1; then
  systemctl daemon-reload || true
  # Never fatal, never silent: a unit left disabled (argos-firewall above all)
  # would only show at the next boot.
  for unit in 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 nginx.service; do
    systemctl enable "$unit" >/dev/null 2>&1 || echo "argos: WARNING — $unit could not be enabled (systemctl enable $unit)" >&2
  done
fi

# Automatic updates are on by default on a fresh appliance (apt drop-ins +
# pinned apt timers, the EDON origin included so argos updates itself). An
# argos policy already on record — on or off — is left untouched.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/updates-default.ts || \
  echo "argos: WARNING — automatic updates could not be configured (Settings → Automatic updates)" >&2

# An account System → Users disabled with the password lock alone (before
# 1.3.1~p20) also gets the expiry: sshd with UsePAM let its SSH keys in.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/users-setup.ts || \
  echo "argos: WARNING — the disabled accounts could not be checked (save them again in System → Users)" >&2

# An appliance installed from an Argos ISO before 1.3.1 quotes the console as
# <address>:8000 in its login banner (/etc/issue and the template the ISO
# renders it from at boot): that line becomes https://<address>/. Nothing on a
# host the ISO never installed.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/issue-setup.ts || \
  echo "argos: WARNING — the login banner could not be checked (/etc/issue)" >&2

# Routing between the zones: switched on (and made persistent) when the
# confirmed argos ruleset already runs; otherwise the first confirmed apply
# does it. Never with no argos filter in the kernel.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/forwarding-setup.ts || \
  echo "argos: WARNING — IPv4 forwarding could not be checked (Status page)" >&2

# The connection table sized from memory, the half-open timeouts shortened
# (DEFCON.md D4): argos's sysctl drop-in, applied now and at every boot.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/conntrack-setup.ts apply || \
  echo "argos: WARNING — the connection table could not be sized (kernel defaults kept)" >&2

# An enabled DNS resolver follows this release's snippet (the blocklist
# include lives where unbound's AppArmor profile lets it read), from the
# cached lists.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/dns-setup.ts || \
  echo "argos: WARNING — the DNS resolver could not be checked (save the DNS page again)" >&2

# An active DPI mode follows this release's Suricata config (Suricata 7 refused
# the one 1.1.36 and older wrote): re-rendered only when it differs. The
# records of the application-recognition plugin argos no longer uses (App-ID
# names applications by itself since 1.3.2~deb14) go first.
rm -f /var/lib/argos/.dpi-ndpi-decision /var/lib/argos/.dpi-ndpi-hold
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/dpi-setup.ts || \
  echo "argos: WARNING — DPI could not be checked (save the DPI page again)" >&2

# Application control follows this release's renders (the generated Suricata
# rules, the zones' DNS views, the argos_appid table): touched only where they
# differ. After the DPI reconcile, which writes the yaml naming the rules file.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/appid-setup.ts || \
  echo "argos: WARNING — application control could not be checked (save the Application control page again)" >&2

# DHCP (one dnsmasq for the scopes and the relays, argos-dhcp.service) follows
# this release's render: rewritten and restarted only when it differs. The
# first pass moves off the Kea argos ran up to 1.2.15 (its running leases
# carried over) and off the relay-only unit; a Kea argos never set up is left
# alone.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/dhcp-setup.ts || \
  echo "argos: WARNING — the DHCP server could not be checked (save the DHCP page again)" >&2

# The IPsec tunnels follow this release's swanctl render (rewritten and
# loaded only where it differs) and get their XFRM interfaces and routes. A
# strongSwan argos never configured is left alone.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/ipsec-setup.ts reconcile || \
  echo "argos: WARNING — the IPsec tunnels could not be checked (save the VPN IPsec page again)" >&2

# The OpenVPN tunnels follow this release's render (rewritten and restarted
# only where it differs) and get their blackhole routes back. Nothing at all
# on a host with no OpenVPN profile; an OpenVPN argos never configured (the
# *.conf of /etc/openvpn) is left alone.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/openvpn-setup.ts reconcile || \
  echo "argos: WARNING — the OpenVPN tunnels could not be checked (save the VPN OpenVPN page again)" >&2

# The Citadel link (Settings → Citadel) follows its stored state: a link that
# is up gets wg-citadel and its timer back, a pending enrollment its timer —
# nothing at all on a host never linked.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/citadel-link.ts reconcile || \
  echo "argos: WARNING — the Citadel link could not be checked (Settings → Citadel)" >&2

# The Atlas link (Settings → Atlas) follows its stored state: a link that is up
# gets wg-atlas and its timer back; an ended one or none, neither (and no
# wg-atlas configuration left behind) — nothing at all on a host never linked.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/atlas-link.ts reconcile || \
  echo "argos: WARNING — the Atlas link could not be checked (Settings → Atlas)" >&2

# EDON Krios (Settings → Krios): an argos Krios deployed carries Krios's deploy
# file from its seed before argos is installed, and a registered one its
# registration; either gets the argos-krios timer, which announces, registers
# and reports. Nothing on a host Krios never knew.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/krios-service.ts reconcile || \
  echo "argos: WARNING — the Krios registration could not be checked (Settings → Krios)" >&2

# The backup on an EDON Atlas (Settings → Backup on Atlas): an enrolled
# appliance gets the pre-backup hook of this release (it records the release
# in the backup's manifest), and the names its agent dials pinned in
# /etc/hosts to the address it reaches Atlas at (PROJECT.md §312) — after
# dns-setup, whose resolv.conf the lookups go through. Nothing on a host
# never enrolled.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/backup-setup.ts reconcile || \
  echo "argos: WARNING — the backup hook could not be checked (Settings → Backup on Atlas)" >&2

# The Atlas satellite's line in /etc/hosts is checked again (never an enrolment,
# never the network); nothing on a host without a satellite.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/hosts-setup.ts || \
  echo "argos: WARNING — /etc/hosts was not checked for the Atlas satellite (the console rewrites it at its next enrolment)" >&2

# The engine itself comes from Debian backports (Suricata 8.x): stable's 7.0
# branch is end-of-life upstream. Detached into its own unit — apt cannot run
# inside this postinst — and skipped when the host is already there.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/dpi-engine.ts || \
  echo "argos: WARNING — the DPI engine was not checked (it stays on Debian stable's Suricata)" >&2

# CrowdSec comes from its official packages, copied into the EDON repository (issue #12): Debian's is frozen at 1.4.6.
# Detached into its own unit like Suricata's, and nothing at all until the repository offers them.
"$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/crowdsec-engine.ts || \
  echo "argos: WARNING — CrowdSec's switch to the official packages was not checked (the console tries again within a day)" >&2

# Debian's stock site answers any Host on :80, which the Let's Encrypt mode
# opens on the WAN: disabled once (an operator may enable it again).
if [ ! -e /var/lib/argos/.nginx-default-disabled ]; then
  if [ -L /etc/nginx/sites-enabled/default ] && [ "$(readlink -f /etc/nginx/sites-enabled/default)" = "/etc/nginx/sites-available/default" ]; then
    rm -f /etc/nginx/sites-enabled/default
  fi
  touch /var/lib/argos/.nginx-default-disabled
fi

# The console moves behind nginx: the site is staged and checked first, then
# the app restarts on 127.0.0.1:3000 (an older release frees its port), nginx
# reloads and the console is probed through it. A failure while nginx still
# runs the configuration that served the console (a reload it refused) keeps
# the console behind it; any other leaves the app answering :80 (or :8000)
# directly (plain http) — never an unreachable console.
if ! "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/console-setup.ts; then
  echo "argos: WARNING — the nginx front was not put in place (see the line above): either nginx still runs its previous configuration and serves the console with it, or the console answers in plain http on :80, or on :8000 while a Reverse proxy holds :80 (fallback). Fix nginx, then run:" >&2
  echo "  $DENO run -A --node-modules-dir=manual /usr/lib/argos/scripts/console-setup.ts" >&2
fi

if command -v systemctl >/dev/null 2>&1; then
  systemctl start argos-tls.timer >/dev/null 2>&1 || true
  systemctl start argos-dns-refresh.timer >/dev/null 2>&1 || true
  systemctl start argos-appid-update.timer >/dev/null 2>&1 || true
  # The catalog's vendor lists are fetched once now, detached: the timer's first
  # run may be a day away, and an appliance should not wait that long for them.
  systemctl start --no-block argos-appid-update.service >/dev/null 2>&1 || true
  # Threat intelligence (info/MISP.md): the table back from the caches at once
  # (`start`: active already after a boot, a no-op), the hourly pass and the
  # minute's watch; the first pass now, detached — a feed download has no place
  # inside dpkg's lock.
  systemctl start argos-intel.service >/dev/null 2>&1 || true
  systemctl start argos-intel-update.timer argos-intel-watch.timer >/dev/null 2>&1 || true
  systemctl start --no-block argos-intel-update.service >/dev/null 2>&1 || true
  # The publications' countries (PROJECT.md §241): the daily refresh, which downloads nothing while no publication
  # asks for a country.
  systemctl start argos-geo-update.timer >/dev/null 2>&1 || true
  # Decoys (info/HONEYPOT.md): the namespace and the quarantine's table at once
  # (`start`: a no-op once the boot pass ran), then put in line with this
  # release's rules; the minute's watch skips itself while no decoy runs.
  systemctl start argos-decoy.service argos-decoy-watch.timer >/dev/null 2>&1 || true
  "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/decoy-setup.ts reconcile || \
    echo "argos: WARNING — the decoys could not be put in line (scripts/decoy-setup.ts reconcile); Protection → Decoys says which" >&2
  # The block page's signing group (PROJECT.md §270): the page's service and its signer carry it
  # (SupplementaryGroups), so it exists before either starts; groupadd where systemd-sysusers cannot run.
  systemd-sysusers /usr/lib/sysusers.d/argos-blockpage-sign.conf >/dev/null 2>&1 || getent group argos-blockpage-sign >/dev/null || \
    groupadd --system argos-blockpage-sign || echo "argos: WARNING — the argos-blockpage-sign group could not be created: the block page's HTTPS will not start" >&2
  # A test build before §271 named the group `argos-blockpage`, the page's own DynamicUser name: systemd refuses a
  # dynamic user whose name a static group holds (217/USER), and the page never starts. Only that static group goes —
  # never one with a static user of the same name.
  if grep -q '^argos-blockpage:' /etc/group 2>/dev/null && ! grep -q '^argos-blockpage:' /etc/passwd 2>/dev/null; then
    groupdel argos-blockpage >/dev/null 2>&1 || echo "argos: WARNING — the argos-blockpage group could not be removed: the block page will not start" >&2
  fi
  # The block page (info/BLOCK-PAGE.md): restarted on this release's code while it is on; never enabled by the
  # package — the console enables it when the operator switches it on.
  "$DENO" run -A --node-modules-dir=manual /usr/lib/argos/scripts/blockpage-setup.ts reconcile || \
    echo "argos: WARNING — the block page could not be put in line (scripts/blockpage-setup.ts reconcile); DNS and DHCP → Block page says why" >&2
  # The two restores are oneshots that only ever ran at boot, so a fresh
  # install left them inactive and the Status page called both down (a danger
  # finding each) until the first reboot. `start`, never `restart`: an
  # appliance that has booted since is already active (exited) and this is a
  # no-op, so an upgrade neither reloads the confirmed ruleset over a pending
  # apply nor re-applies the routes. A fresh install has nothing confirmed and
  # no routes on record: both exit 0 having done nothing. Before the monitor,
  # the order argos-network declares (Before=argos-wan-monitor.service).
  if ! systemctl start argos-firewall.service >/dev/null 2>&1; then
    echo "argos: WARNING — argos-firewall.service failed: the confirmed ruleset was refused, so the emergency one (management ports only) runs (systemctl status argos-firewall.service)" >&2
  fi
  if ! systemctl start argos-network.service >/dev/null 2>&1; then
    echo "argos: WARNING — argos-network.service failed: a static route, an uplink default, a policy rule or a shaping class was not re-applied (systemctl status argos-network.service)" >&2
  fi
  # Probe-based failover must not wait for a reboot: a fresh install never
  # started the monitor, an upgrade from 1.1.12 or older had its prerm stop it.
  if ! systemctl restart argos-wan-monitor.service >/dev/null 2>&1; then
    echo "argos: WARNING — argos-wan-monitor.service did not start: probe-based WAN failover is off (systemctl status argos-wan-monitor.service)" >&2
  fi
fi

exit 0
