#!/usr/bin/env bash
# silverguard-node/apply — run (or re-converge) a SilverGUARD (npm-net) edge engine on this node.
# Run by role-helper as root; params JSON on stdin; outputs → $SSR_OUTPUTS. Idempotent.
# NEVER echo secrets: registry/admin passwords and the JWT key stay out of the log and outputs.
#
# params:
#   bindIps           ["82.39.133.233", ...] — public IPs that get :80/:443. Never 0.0.0.0: other
#                     roles on the box (e.g. vpn-exit's xray) own :443 on their own IPs.
#   imageTag          npm-net tag in registry.silverlined.uk (e.g. 1.5.13)
#   registryUser / registryPassword   pull credentials for registry.silverlined.uk
#   instanceId / instanceName         e.g. silverguard-vm6 / "SilverGUARD vm6-node2"
#   adminEmail / adminPassword        engine admin (the agent's npmnet relay logs in with these)
#   acmeEmail         default admin@silverlined.uk
# outputs: instanceId, version, adminUrl, bindIps
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)
p() { jq -r --arg k "$1" '.[$k] // empty' <<<"$P"; }
die() { echo "ERROR: $*" >&2; exit 1; }
mapfile -t BIND_IPS < <(jq -r '.bindIps[]? // empty' <<<"$P")
TAG=$(p imageTag); RU=$(p registryUser); RP=$(p registryPassword)
IID=$(p instanceId); INAME=$(p instanceName); AE=$(p adminEmail); AP=$(p adminPassword)
ACME=$(p acmeEmail); ACME=${ACME:-admin@silverlined.uk}
((${#BIND_IPS[@]})) || die "bindIps required"
for v in TAG RU RP IID AE AP; do [[ -n "${!v}" ]] || die "missing param $v"; done
[[ "$IID" =~ ^[a-z0-9-]{3,40}$ ]] || die "instanceId must be [a-z0-9-]"
[[ "$TAG" =~ ^[A-Za-z0-9._-]+$ ]] || die "bad imageTag"
INAME=${INAME:-SilverGUARD $IID}
INAME=$(tr -cd 'A-Za-z0-9 ._()-' <<<"$INAME")
DIR=/opt/silverguard
IMAGE="registry.silverlined.uk/npm-net:$TAG"

echo "== preflight"
command -v docker >/dev/null && docker compose version >/dev/null 2>&1 || die "docker + compose v2 required"
for ip in "${BIND_IPS[@]}"; do
  [[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "bad bind IP $ip"
  ip -4 -o addr show | grep -qw "inet $ip" || die "bind IP $ip is not configured on this host"
  for port in 80 443; do
    owner=$(ss -Hltnp "sport = :$port" | awk -v a="$ip:$port" -v w="0.0.0.0:$port" -v s="*:$port" '$4==a||$4==w||$4==s' | grep -v docker-proxy || true)
    [[ -z "$owner" ]] || die "$ip:$port already in use: $owner"
  done
done

echo "== registry login + pull $IMAGE"
printf '%s' "$RP" | docker login registry.silverlined.uk -u "$RU" --password-stdin >/dev/null
docker pull -q "$IMAGE" >/dev/null

echo "== compose"
install -d -m 750 "$DIR"
if [[ ! -s "$DIR/.env" ]] || ! grep -q '^SILVERGUARD_JWT_KEY=' "$DIR/.env"; then
  ( umask 077; printf 'SILVERGUARD_JWT_KEY=%s\n' "$(head -c 64 /dev/urandom | base64 | tr -d '\n/+=' | cut -c1-48)" > "$DIR/.env" )
fi
chmod 600 "$DIR/.env"
NEW=$(mktemp)
{
  echo "# managed by silvershell role silverguard-node — re-run the role instead of editing"
  echo "services:"
  echo "  silverguard:"
  echo "    image: $IMAGE"
  echo "    container_name: silverguard"
  echo "    restart: unless-stopped"
  echo "    mem_limit: 768m"
  echo "    ports:"
  for ip in "${BIND_IPS[@]}"; do
    echo "      - \"$ip:80:80\""
    echo "      - \"$ip:443:443\""
  done
  echo "      - \"127.0.0.1:81:81\""
  echo "    extra_hosts:"
  echo "      - \"host.docker.internal:host-gateway\""
  echo "    environment:"
  echo "      - ASPNETCORE_ENVIRONMENT=Production"
  echo "      - ConnectionStrings__DefaultConnection=Data Source=/data/npm-net.db"
  echo "      - INSTANCE_ID=$IID"
  echo "      - INSTANCE_NAME=$INAME"
  echo "      - Clustering__Enabled=false"
  echo "      - Clustering__NodeId=$IID"
  echo "      - Clustering__NodeName=$INAME"
  echo '      - Jwt__Key=${SILVERGUARD_JWT_KEY:?set SILVERGUARD_JWT_KEY in .env}'
  echo "      - Jwt__Issuer=SilverGUARD"
  echo "      - Jwt__Audience=SilverGUARD"
  echo "      - LetsEncrypt__Email=$ACME"
  echo "      - LetsEncrypt__UseStaging=false"
  echo "      - Nginx__ConfigPath=/etc/nginx/conf.d"
  echo "      - Nginx__CertPath=/etc/letsencrypt/live"
  echo "    volumes:"
  echo "      - silverguard-data:/data"
  echo "      - silverguard-letsencrypt:/etc/letsencrypt"
  echo "      - silverguard-conf:/etc/nginx/conf.d"
  echo "    healthcheck:"
  echo "      test: [\"CMD\", \"curl\", \"-fsS\", \"http://127.0.0.1:81/health\"]"
  echo "      interval: 30s"
  echo "      timeout: 5s"
  echo "      retries: 5"
  echo "      start_period: 40s"
  echo "    networks:"
  echo "      - edge"
  echo ""
  echo "# Co-located backends join \"silverguard-edge\" and are addressed by container name"
  echo "# (127.0.0.1-published ports are unreachable from the bridge)."
  echo "networks:"
  echo "  edge:"
  echo "    name: silverguard-edge"
  echo ""
  echo "volumes:"
  echo "  silverguard-data:"
  echo "  silverguard-letsencrypt:"
  echo "  silverguard-conf:"
} > "$NEW"
install -m 640 "$NEW" "$DIR/docker-compose.yml"; rm -f "$NEW"
docker compose -f "$DIR/docker-compose.yml" --project-directory "$DIR" -p silverguard up -d --remove-orphans

echo "== wait for health"
for _ in $(seq 1 60); do curl -fsS -m 3 http://127.0.0.1:81/health >/dev/null 2>&1 && break; sleep 2; done
curl -fsS -m 3 http://127.0.0.1:81/health >/dev/null || die "engine not healthy on 127.0.0.1:81"

B=http://127.0.0.1:81
login() {
  curl -fsS -m 15 -X POST "$B/api/auth/login" -H 'Content-Type: application/json' \
    -d "$(jq -cn --arg e "$1" --arg p "$2" '{email:$e,password:$p}')" 2>/dev/null | jq -r '.token // empty'
}
call() { # method token path [json]
  if [[ -n "${4:-}" ]]; then
    curl -fsS -m 30 -X "$1" "$B$3" -H "Authorization: Bearer $2" -H 'Content-Type: application/json' -d "$4"
  else
    curl -fsS -m 30 -X "$1" "$B$3" -H "Authorization: Bearer $2"
  fi
}

echo "== bootstrap admin"
TOK=$(login "$AE" "$AP" || true)
if [[ -z "$TOK" ]]; then
  SEED=$(login admin@example.com changeme || true)
  [[ -n "$SEED" ]] || die "neither the admin nor the seed account can log in (engine bootstrapped with other credentials?)"
  call POST "$SEED" /api/auth/register \
    "$(jq -cn --arg e "$AE" --arg p "$AP" '{email:$e,name:"SilverLined platform",password:$p,roles:["admin"]}')" >/dev/null
  TOK=$(login "$AE" "$AP"); [[ -n "$TOK" ]] || die "new admin login failed"
  echo "admin created"
else
  echo "admin already present"
fi
# Retire the seed admin. npm-net <= 1.5.13 500s on deleting an admin (untranslatable last-admin
# query, fixed in npm-net #31), so fall back to scrambling its password (no last-admin check).
SID=$(call GET "$TOK" /api/users | jq -r '.[] | select(.email=="admin@example.com") | .id')
if [[ -n "$SID" ]]; then
  if call DELETE "$TOK" "/api/users/$SID" >/dev/null 2>&1; then
    echo "seed admin deleted"
  else
    call POST "$TOK" "/api/users/$SID/reset-password" \
      "$(jq -cn --arg p "$(head -c 48 /dev/urandom | base64 | tr -d '\n/+=')" '{newPassword:$p}')" >/dev/null
    echo "seed admin could not be deleted; password scrambled"
  fi
fi

echo "== letsencrypt provider config"
LEID=$(call GET "$TOK" /api/certificateproviderconfigs | jq -r '.[] | select(.providerType=="letsencrypt") | .id' | head -1)
if [[ -z "$LEID" ]]; then
  call POST "$TOK" /api/certificateproviderconfigs \
    "$(jq -cn --arg m "$ACME" '{name:"Lets Encrypt (production)",providerType:"letsencrypt",isActive:true,priority:1,useStaging:false,acmeEmail:$m}')" >/dev/null
  echo "created"
else
  echo "present"
fi

echo "== agent npmnet engine credentials"
T=/etc/silvershell-agent/agent.toml
NEWT=$(mktemp)
# $(...) trims trailing blank lines, so re-runs produce byte-identical output (no restart loop).
REST=$(awk 'BEGIN{skip=0} /^\[/{skip=($0=="[plugins.npmnet]")} !skip' "$T")
printf '%s\n\n[plugins.npmnet]\nenabled = true\nengine_url = "http://127.0.0.1:81"\nengine_email = "%s"\nengine_password = "%s"\n' "$REST" "$AE" "$AP" > "$NEWT"
if ! cmp -s "$NEWT" "$T"; then
  install -m 640 -o root -g silvershell-agent "$NEWT" "$T"
  # 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.toml updated; agent restart scheduled in 20s"
fi
rm -f "$NEWT"

VER=$(curl -fsS -m 5 "$B/api/version" 2>/dev/null | jq -r '.version // .Version // empty' 2>/dev/null || true)
if [[ -n "${SSR_OUTPUTS:-}" ]]; then
  jq -n --arg i "$IID" --arg v "${VER:-$TAG}" --argjson ips "$(printf '%s\n' "${BIND_IPS[@]}" | jq -R . | jq -s .)" \
    '{instanceId:$i, version:$v, adminUrl:"http://127.0.0.1:81", bindIps:$ips}' > "$SSR_OUTPUTS"
fi
echo "== silverguard-node applied ($IID, $IMAGE on ${BIND_IPS[*]})"
