#!/usr/bin/env bash
# hosting-node/apply — make this node able to run SilverDESK web-hosting packages.
# Run by role-helper as root; params JSON on stdin; outputs → $SSR_OUTPUTS. Idempotent.
#
# What it does (the Docker + SiteProxy plugins themselves arrive via Module Library pins):
#   - installs the Docker engine when missing (docker.io + compose plugin)
#   - lets the unprivileged agent drive docker (supplementary group, like the lab hostservers)
#   - pins the siteproxy front door to ONE public IP ([plugins.siteproxy] bind_ip), so it can
#     share the box with other roles that own :80 on their own IPs (silverguard-node, vpn-exit)
#   - schedules an agent restart when anything changed
#
# params:
#   bindIp   "82.39.133.181" — public IPv4 the siteproxy publishes :80 on (never 0.0.0.0)
# outputs: bindIp, dockerGroup
set -euo pipefail
umask 022
command -v jq >/dev/null || { DEBIAN_FRONTEND=noninteractive apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends jq; } >&2
P=$(cat)
die() { echo "ERROR: $*" >&2; exit 1; }
IP=$(jq -r '.bindIp // empty' <<<"$P")
AGENT_USER=silvershell-agent
T=/etc/silvershell-agent/agent.toml
SP=silver-siteproxy

echo "== preflight"
[[ "$IP" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "bindIp must be an IPv4 address"
ip -4 -o addr show | grep -qw "inet $IP" || die "bind IP $IP is not configured on this host"
if ! command -v docker >/dev/null 2>&1; then
  # A customer's own server usually arrives without Docker (the one-liner installs only the agent).
  # Same distro packages install-agent.sh WITH_DOCKER=1 uses: engine + compose v2 plugin. INSTALL LAW: no Recommends.
  echo "installing docker engine (docker.io + docker-compose)"
  { DEBIAN_FRONTEND=noninteractive apt-get update -qq     && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends docker.io docker-compose; } >&2     || die "could not install docker (apt-get install docker.io docker-compose failed)"
  systemctl enable --now docker >&2 || die "docker service failed to start"
fi
docker info >/dev/null 2>&1 || die "docker engine installed but not running (docker info failed)"
getent group docker >/dev/null || die "docker group missing"
# :80 on our IP (or the wildcard) must be free, or already ours.
owner=$(ss -Hltnp "sport = :80" | awk -v a="$IP:80" -v w="0.0.0.0:80" -v s="*:80" '$4==a||$4==w||$4==s' | grep -v docker-proxy || true)
[[ -z "$owner" ]] || die "$IP:80 already in use: $owner"
for c in $(docker ps -q); do
  name=$(docker inspect -f '{{.Name}}' "$c" | sed 's#^/##')
  [[ "$name" == "$SP" ]] && continue
  if docker inspect -f '{{range $p, $b := .HostConfig.PortBindings}}{{range $b}}{{$p}}={{.HostIp}} {{end}}{{end}}' "$c" \
      | tr ' ' '\n' | grep -E '^80/tcp=' | grep -qE "=($IP|0\.0\.0\.0|)$"; then
    die "container $name already publishes :80 on $IP (or all interfaces)"
  fi
done

CHANGED=0

echo "== agent docker access"
if id -nG "$AGENT_USER" | tr ' ' '\n' | grep -qx docker; then
  echo "already in docker group"
else
  usermod -aG docker "$AGENT_USER"
  CHANGED=1
  echo "added $AGENT_USER to docker group"
fi

echo "== siteproxy bind ip"
NEWT=$(mktemp)
# $(...) trims trailing blank lines, so re-runs produce byte-identical output (no restart loop).
REST=$(awk 'BEGIN{skip=0} /^\[/{skip=($0=="[plugins.siteproxy]")} !skip' "$T")
printf '%s\n\n[plugins.siteproxy]\nenabled = true\nbind_ip = "%s"\n' "$REST" "$IP" > "$NEWT"
if ! cmp -s "$NEWT" "$T"; then
  install -m 640 -o root -g "$AGENT_USER" "$NEWT" "$T"
  CHANGED=1
  echo "agent.toml updated"
else
  echo "agent.toml already current"
fi
rm -f "$NEWT"

# A siteproxy container created before bind_ip keeps its old (all-interfaces) publish:
# the plugin only `docker start`s an existing container. Drop it so the plugin recreates it.
if docker inspect "$SP" >/dev/null 2>&1; then
  cur=$(docker inspect -f '{{range (index .HostConfig.PortBindings "80/tcp")}}{{.HostIp}}{{end}}' "$SP" 2>/dev/null || true)
  if [[ "$cur" != "$IP" ]]; then
    docker rm -f "$SP" >/dev/null
    CHANGED=1
    echo "removed $SP (published on '${cur:-*}'); the plugin recreates it on $IP"
  fi
fi

if (( CHANGED )); then
  # Restart AFTER this role has reported back (the agent is waiting on our result file).
  systemd-run --quiet --on-active=20 --unit "ssa-restart-$(date +%s)" systemctl restart silvershell-agent
  echo "agent restart scheduled in 20s"
fi

if [[ -n "${SSR_OUTPUTS:-}" ]]; then
  jq -n --arg ip "$IP" '{bindIp:$ip, dockerGroup:true}' > "$SSR_OUTPUTS"
fi
echo "== hosting-node applied (siteproxy on $IP:80)"
