#!/usr/bin/env bash
# platform-sdp-host/apply — SilverDotPay host: tor, the CI forced-command deploy hook, its config.
# The compose project itself is written by SilverDESK (docker.compose.up); this role never writes it.
# Run by role-helper as root; params JSON on stdin; outputs -> $SSR_OUTPUTS (no secrets).
#
# params: {"projectName":"silverdotpay" (optional),"projectDir":"/var/lib/silvershell-agent/compose/silverdotpay","healthUrl":"http://10.13.13.20:5100/health",
#          "ciDeployPubKey":"ssh-ed25519 …","ciDeployFrom":"82.8.176.11,10.0.0.0/8","torSocksListen":"172.17.0.1:9060" (optional)}
# outputs: torVersion, torActive, deployHook
set -euo pipefail
umask 022
HERE="$(cd "$(dirname "$0")" && pwd)"
. "$HERE/../lib/authkeys.sh"
P=$(cat)
die() { echo "ERROR: $*" >&2; exit 1; }
ETC="${SSR_ETC:-/etc}"; RHOME="${SSR_ROOT_HOME:-/root}"; SBIN="${SSR_SBIN:-/usr/local/sbin}"
TAG=platform-sdp-host

PROJECT=$(jq -r '.projectDir // empty' <<<"$P")
HEALTH=$(jq -r '.healthUrl // empty' <<<"$P")
NAME=$(jq -r '.projectName // "silverdotpay"' <<<"$P")
PUB=$(jq -r '.ciDeployPubKey // empty' <<<"$P")
FROM=$(jq -r '.ciDeployFrom // empty' <<<"$P")
SOCKS=$(jq -r '.torSocksListen // empty' <<<"$P")

[[ "$PROJECT" =~ ^/[A-Za-z0-9._/-]+$ ]] && [[ "$PROJECT/" != *"/../"* ]] || die "projectDir must be an absolute path without .. components"
[[ "$NAME" =~ ^[a-z0-9][a-z0-9_-]{0,62}$ ]] || die "projectName invalid"
[[ "$HEALTH" =~ ^https?://[A-Za-z0-9._:/?=\&%-]+$ ]] || die "healthUrl must be an http(s) URL"
# ciDeployPubKey is optional: without it no CI deploy key is accepted (drill boxes) and an existing managed block is removed.
if [ -n "$PUB" ]; then
  [[ "$PUB" != *$'\n'* && "$PUB" != *$'\r'* ]] || die "ciDeployPubKey must be a single line"
  authkeys_valid_pubkey "$PUB" || die "ciDeployPubKey is not a valid OpenSSH public key"
  authkeys_valid_from "$FROM" || die "ciDeployFrom is required (addresses/CIDRs, comma separated)"
fi
if [ -n "$SOCKS" ]; then
  [[ "$SOCKS" =~ ^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}:[0-9]{1,5}$ ]] \
    && [ "${SOCKS##*:}" -ge 1 ] && [ "${SOCKS##*:}" -le 65535 ] || die "torSocksListen must be IPv4:port"
fi

apt-get install -y --no-install-recommends tor
systemctl enable --now tor

# Optional SOCKS listener for the SilverDotPay containers (docker bridge address), as a managed torrc block.
# Identical hand-added lines outside the block are dropped so tor never sees a duplicate SocksPort.
if [ -n "$SOCKS" ]; then
  TORRC="$ETC/tor/torrc"
  [ -f "$TORRC" ] || : > "$TORRC"
  want=$(printf '%s\n' "SocksPort $SOCKS" "SocksPolicy accept 172.16.0.0/12" "SocksPolicy reject *" "ExitRelay 0" "ExitPolicy reject *:*")
  tmp=$(mktemp "$ETC/tor/.torrc.XXXXXX")
  awk -v tag="$TAG" -v want="$want" '
    BEGIN { n = split(want, w, "\n"); for (i = 1; i <= n; i++) drop[w[i]] = 1 }
    { sub(/\r$/, "") }
    $0 == "# BEGIN silverlined " tag { skip = 1; next }
    $0 == "# END silverlined " tag   { skip = 0; next }
    skip || ($0 in drop) { next }
    { print }
    END { print "# BEGIN silverlined " tag; for (i = 1; i <= n; i++) print w[i]; print "# END silverlined " tag }
  ' "$TORRC" > "$tmp"
  chmod 0644 "$tmp"
  if cmp -s "$tmp" "$TORRC"; then rm -f "$tmp"; else mv "$tmp" "$TORRC"; systemctl restart tor; fi
fi

install -d -m 0755 "$SBIN" "$ETC/silverlined"
install -m 0755 "$HERE/sdp-deploy" "$SBIN/sdp-deploy"
printf 'projectDir=%s\nprojectName=%s\nhealthUrl=%s\n' "$PROJECT" "$NAME" "$HEALTH" > "$ETC/silverlined/sdp-deploy.conf"
chmod 0644 "$ETC/silverlined/sdp-deploy.conf"

if [ -n "$PUB" ]; then
  mkdir -p "$RHOME/.ssh"; chmod 0700 "$RHOME/.ssh"
  authkeys_set_block "$RHOME/.ssh/authorized_keys" "$TAG"     "command=\"/usr/local/sbin/sdp-deploy\",from=\"$FROM\",no-pty,no-port-forwarding,no-agent-forwarding,no-X11-forwarding $PUB"
else
  authkeys_remove_block "$RHOME/.ssh/authorized_keys" "$TAG"
fi

TORV=$(tor --version 2>/dev/null | sed -n '1s/^Tor version \([0-9][0-9.]*[0-9]\).*/\1/p' || true)
ACTIVE=false; if systemctl is-active --quiet tor; then ACTIVE=true; fi
jq -n --arg v "${TORV:-}" --argjson a "$ACTIVE" '{torVersion:$v,torActive:$a,deployHook:"/usr/local/sbin/sdp-deploy"}' > "$SSR_OUTPUTS"
echo "sdp host ready (tor ${TORV:-?}, active=$ACTIVE)"
