#!/usr/bin/env bash
# platform-apt-host/apply — aptly + gnupg APT publishing host: publish user, forced-restriction SSH key,
# sudo for aptly only, signing key imported from stdin, aptly config.
# Run by role-helper as root; params JSON on stdin; outputs -> $SSR_OUTPUTS (world-readable: NO secrets).
#
# params: {"dataDir":"/srv/apt","publishUser":"sysadmin","publishPubKey":"ssh-ed25519 AAAA… ci",
#          "publishFrom":"82.8.176.11,10.0.0.0/8","signingKey":"<ascii-armored secret key>","origin":"silverlabs"}
# outputs: aptlyVersion, signingKeyFingerprint, publishUser, aptlyConf
# NOTE: this role OWNS /root/.aptly.conf; it is rewritten on every apply (do not hand-edit).
set -euo pipefail
umask 022   # sensitive files get explicit modes below
HERE="$(cd "$(dirname "$0")" && pwd)"
. "$HERE/../lib/authkeys.sh"
P=$(cat)
die() { echo "ERROR: $*" >&2; exit 1; }
ETC="${SSR_ETC:-/etc}"; HOMES="${SSR_HOME_ROOT:-/home}"; RHOME="${SSR_ROOT_HOME:-/root}"
TAG=platform-apt-host

DATA=$(jq -r '.dataDir // "/srv/apt"' <<<"$P")
USR=$(jq -r '.publishUser // empty' <<<"$P")
PUB=$(jq -r '.publishPubKey // empty' <<<"$P")
FROM=$(jq -r '.publishFrom // empty' <<<"$P")
SKEY=$(jq -r '.signingKey // empty' <<<"$P")
ORIGIN=$(jq -r '.origin // "silverlabs"' <<<"$P")

# ---- validate everything before changing anything
[[ "$USR" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || die "publishUser invalid"
[[ "$DATA" =~ ^/[A-Za-z0-9._/-]+$ ]] && [[ "$DATA/" != *"/../"* ]] || die "dataDir must be an absolute path without .. components"
# publishPubKey is optional: without it no publish key is accepted (drill boxes) and an existing managed block is removed.
if [ -n "$PUB" ]; then
  [[ "$PUB" != *$'\n'* && "$PUB" != *$'\r'* ]] || die "publishPubKey must be a single line"
  authkeys_valid_pubkey "$PUB" || die "publishPubKey is not a valid OpenSSH public key"
  authkeys_valid_from "$FROM" || die "publishFrom is required (addresses/CIDRs, comma separated)"
fi
[[ "$ORIGIN" =~ ^[A-Za-z0-9._-]{1,64}$ ]] || die "origin invalid"

GPG="${SSR_GPG_CMD:-gpg}"
# primary secret-key fingerprints in the keyring (empty when gpg is missing or there is none)
secret_fprs() { "$GPG" --batch --list-secret-keys --with-colons 2>/dev/null | awk -F: '$1=="sec"{s=1} $1=="fpr"&&s{print toupper($10); s=0}' || true; }
install_pkgs() { apt-get install -y --no-install-recommends aptly gnupg; }

FPR=""
if [ -n "$SKEY" ]; then
  # gnupg may not be installed yet on a fresh host: install before touching gpg
  install_pkgs
  info=$(printf '%s\n' "$SKEY" | "$GPG" --batch --show-keys --with-colons 2>/dev/null) || die "signingKey is not a valid key"
  grep -q '^sec:' <<<"$info" || die "signingKey is not a secret key"
  FPR=$(awk -F: '$1=="fpr"{print toupper($10); exit}' <<<"$info")
  [[ "$FPR" =~ ^[0-9A-F]{40}$ ]] || die "could not read signing key fingerprint"
  existing=$(secret_fprs)
  if [ -n "$existing" ] && ! grep -qx "$FPR" <<<"$existing"; then
    die "a different signing key is already in the keyring: $(head -n 1 <<<"$existing")"
  fi
else
  command -v "$GPG" >/dev/null 2>&1 || die "signingKey is required: no secret key in the keyring yet"
  FPR=$(secret_fprs | head -n 1)
  [ -n "$FPR" ] || die "signingKey is required: no secret key in the keyring yet"
  install_pkgs
fi

# ---- user
if ! id -u "$USR" >/dev/null 2>&1; then useradd -m -s /bin/bash "$USR"; fi
if [ -n "${SSR_HOME_ROOT:-}" ]; then UHOME="$HOMES/$USR"; else UHOME=$(getent passwd "$USR" | cut -d: -f6); fi
[ -n "$UHOME" ] || die "cannot resolve the home directory of $USR"
authkeys_refuse_symlinks "$UHOME/.ssh/authorized_keys" || exit 1
[ ! -L "$UHOME/.ssh" ] || die "$UHOME/.ssh is a symlink"
if [ -n "$PUB" ]; then
  install -d -m 0700 "$UHOME/.ssh"
  authkeys_set_block "$UHOME/.ssh/authorized_keys" "$TAG" "from=\"$FROM\",no-pty,no-port-forwarding,no-agent-forwarding $PUB"
  chown -R "$USR:" "$UHOME/.ssh" 2>/dev/null || true
else
  authkeys_remove_block "$UHOME/.ssh/authorized_keys" "$TAG"
fi

# ---- sudo: aptly only (validated before it is moved into place)
[ -d "$ETC/sudoers.d" ] || install -d -m 0750 "$ETC/sudoers.d"
SUD="$ETC/sudoers.d/silverlabs-aptly"; TMP="$ETC/sudoers.d/.silverlabs-aptly.tmp"
( umask 077; printf '%s ALL=(root) NOPASSWD: /usr/bin/aptly *\n' "$USR" > "$TMP" )
chmod 0440 "$TMP"
if ! visudo -cf "$TMP" >/dev/null; then rm -f "$TMP"; die "sudoers validation failed"; fi
mv -f "$TMP" "$SUD"

# ---- signing key (stdin only; same fingerprint already present = no-op)
if [ -n "$SKEY" ] && ! secret_fprs | grep -qx "$FPR"; then
  printf '%s\n' "$SKEY" | "$GPG" --batch --import >/dev/null 2>&1 || die "gpg key import failed"
fi

# ---- aptly config + data (public must be world-traversable so a web server can serve it; aptly state stays root-only)
install -d -m 0755 "${SSR_DATA_PREFIX:-}$DATA" "${SSR_DATA_PREFIX:-}$DATA/public" "$RHOME" "$ETC/silverlined"
install -d -m 0700 "${SSR_DATA_PREFIX:-}$DATA/aptly"
MSYS_NO_PATHCONV=1 jq -n --arg r "$DATA/aptly" --arg p "$DATA/public" \
  '{rootDir:$r,FileSystemPublishEndpoints:{public:{rootDir:$p,linkMethod:"hardlink",verifyMethod:"md5"}}}' > "$RHOME/.aptly.conf"
chmod 0644 "$RHOME/.aptly.conf"
MSYS_NO_PATHCONV=1 jq -n --arg d "$DATA" --arg o "$ORIGIN" '{dataDir:$d,origin:$o}' > "$ETC/silverlined/platform-apt-host.conf"
chmod 0644 "$ETC/silverlined/platform-apt-host.conf"

VER=$(aptly version | awk '{print $NF}')
jq -n --arg v "$VER" --arg f "$FPR" --arg u "$USR" '{aptlyVersion:$v,signingKeyFingerprint:$f,publishUser:$u,aptlyConf:"/root/.aptly.conf"}' > "$SSR_OUTPUTS"
echo "apt host ready (aptly $VER, key $FPR)"
