#!/usr/bin/env bash
# idss-broker-install — the droplet-side install leg of the broker's auto-deploy
# rail (#688, ADR 0185). Installed to /usr/local/sbin/idss-broker-install
# (root:755) on the mail droplet and invoked by the `deploy` user through one
# sudoers line:
#
#     deploy ALL=(root) NOPASSWD: /usr/local/sbin/idss-broker-install *
#
# It is the broker's equivalent of scripts/bootstrap-reseed/reseed.sh's install
# step: pull a per-sha `ourcloud-broker` binary from the Forgejo generic package
# registry (anonymous read — the registry is public-read today), sanity-check it,
# atomically swap it in, restart the unit, and PROVE the new broker is live
# (`is-active` AND a 200 from /v1/gateways/offer) within a bounded wait. If the
# new binary does not come up, the RUNNING binary is restored from a backup and
# the unit restarted, and the script exits non-zero so `broker-deploy` goes red
# and journalctl still shows the OLD (working) version. Never a half-deployed
# broker (the ADR 0047 no-half-rented-server discipline, applied to the deploy).
#
# Usage:
#     idss-broker-install <fullsha>
#
# The <fullsha> is the git sha CI published the binary under (registry package
# `idss-broker/<fullsha>/ourcloud-broker-x86_64`). Idempotent: re-installing the
# sha already running is a no-op (verified live, then exit 0).
#
# Env (all have production defaults; the offline test overrides them):
#   BROKER_REGISTRY_SERVER   default https://git.matou.nz
#   BROKER_REGISTRY_OWNER    default Matou
#   BROKER_REGISTRY_PACKAGE  default idss-broker
#   BROKER_REGISTRY_TOKEN    optional; only if the registry read ever needs auth
#   BROKER_ARCH              default x86_64
#   BROKER_BIN               default /usr/local/bin/ourcloud-broker
#   BROKER_SERVICE           default ourcloud-broker
#   BROKER_HEALTH_URL        default http://127.0.0.1:8090/v1/gateways/offer
#   BROKER_VERSION_MARKER    default alpha-rentals   (a `strings` marker that
#                            proves the download is a real broker build carrying
#                            a version, not an HTML 404 page; bump when the
#                            broker leaves the alpha-rentals line)
#   BROKER_HEALTH_TIMEOUT    default 10   (seconds to wait for is-active + offer)
#   BROKER_HEALTH_INTERVAL   default 1    (seconds between health polls)
#   BROKER_BACKUP_KEEP       default 3    (how many .bak-<sha> backups to keep)
set -euo pipefail

server="${BROKER_REGISTRY_SERVER:-https://git.matou.nz}"
owner="${BROKER_REGISTRY_OWNER:-Matou}"
package="${BROKER_REGISTRY_PACKAGE:-idss-broker}"
arch="${BROKER_ARCH:-x86_64}"
bin="${BROKER_BIN:-/usr/local/bin/ourcloud-broker}"
service="${BROKER_SERVICE:-ourcloud-broker}"
health_url="${BROKER_HEALTH_URL:-http://127.0.0.1:8090/v1/gateways/offer}"
marker="${BROKER_VERSION_MARKER:-alpha-rentals}"
health_timeout="${BROKER_HEALTH_TIMEOUT:-10}"
health_interval="${BROKER_HEALTH_INTERVAL:-1}"
backup_keep="${BROKER_BACKUP_KEEP:-3}"
# This very script's on-disk path on the droplet — the drift alarm (#872) checks
# it against the installer CI published for the sha. Overridable so the offline
# test can point it at a fixture (and so an ad-hoc run from a checkout, where the
# path does not exist, skips the check).
install_self="${BROKER_INSTALL_SELF:-/usr/local/sbin/idss-broker-install}"
# Where the unit's "build <sha>" Description drop-in is written, so `systemctl
# status` names the binary that is actually live. The unit file itself was hand-
# placed with a literal "build 86d5ef7" that outlived four deploys' worth of
# binaries; a drop-in is re-stamped on every install (and rollback) instead.
unit_dropin_dir="${BROKER_UNIT_DROPIN_DIR:-/etc/systemd/system/${service}.service.d}"

# Optional bearer for the anonymous registry reads (both the per-sha binary and
# the installer-drift fetch below); empty by default — the generic registry is
# public-read, and the write token 401s on read (broker-publish-lib.sh #864).
auth=()
[ -n "${BROKER_REGISTRY_TOKEN:-}" ] && auth=(-H "Authorization: token ${BROKER_REGISTRY_TOKEN}")

# The sha of the binary currently installed is recorded next to it, so an install
# can name the backup it displaces and short-circuit an already-installed sha.
sha_file="${bin}.sha"

log() { echo "idss-broker-install: $*"; }
die() { echo "idss-broker-install: $*" >&2; exit 1; }

installed_sha() { cat "$sha_file" 2>/dev/null || true; }

# The offer probe through a PROXY-protocol listener. The deployed broker runs
# BROKER_PROXY_PROTOCOL=1 (#2010, ADR 0253): it drops every connection that does
# not open with a PROXY v2 header, so a plain curl is "reset by peer" against a
# perfectly healthy broker — every deploy since #2010 read the live broker as dead
# and tried to roll back (GOTCHAS #419). curl's --haproxy-protocol speaks only v1,
# which broker/internal/proxyproto refuses, so the 16-byte v2 LOCAL header
# (proxyproto.HeaderV2Local: signature, ver 2 / LOCAL, UNSPEC, length 0) is written
# by hand ahead of a minimal GET. 0 on an HTTP 200, non-zero otherwise.
probe_proxy_v2() {
  local rest="${health_url#http://}" hostport path host port
  hostport="${rest%%/*}"
  if [ "$rest" = "$hostport" ]; then path="/"; else path="/${rest#*/}"; fi
  host="${hostport%:*}"; port="${hostport##*:}"
  [ "$port" = "$hostport" ] && port=80
  timeout 5 bash -c '
    exec 3<>"/dev/tcp/$1/$2" || exit 1
    printf "\r\n\r\n\0\r\nQUIT\n\x20\x00\x00\x00" >&3
    printf "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" "$3" "$1" >&3
    IFS= read -r line <&3 || exit 1
    case "$line" in "HTTP/1."?" 200"*) exit 0;; *) exit 1;; esac
  ' _ "$host" "$port" "$path" 2>/dev/null
}

# is-active AND a 200 from the offer face — the broker is "up" only when it both
# runs and answers. A plain request is tried first (a direct listener), then the
# PROXY v2 one (the deployed, proxied listener). Returns 0 when live.
broker_live() {
  systemctl is-active --quiet "$service" || return 1
  curl -fsS --max-time 5 -o /dev/null "$health_url" 2>/dev/null && return 0
  probe_proxy_v2 && return 0
  return 1
}

# Poll broker_live for up to health_timeout seconds. 0 = came up, 1 = never did.
# Stamp the unit's Description with the sha that is live. Best-effort: a failure
# here must never fail (or roll back) a deploy — the binary is already correct.
stamp_build() { # <sha>
  local sha="$1"
  mkdir -p "$unit_dropin_dir" || { log "could not create $unit_dropin_dir — build stamp skipped"; return 0; }
  printf '[Unit]\nDescription=OurCloud subdomain broker (idss.nz zone, ADR 0128) — build %s\n' "${sha:0:12}" \
    > "$unit_dropin_dir/build.conf" || { log "could not write build stamp — skipped"; return 0; }
  systemctl daemon-reload || log "daemon-reload returned non-zero — the stamp lands on the next reload"
}

wait_live() {
  local waited=0
  while :; do
    if broker_live; then return 0; fi
    [ "$waited" -ge "$health_timeout" ] && return 1
    sleep "$health_interval"
    waited=$((waited + health_interval))
  done
}

# Keep only the newest $backup_keep `<bin>.bak-*` backups; delete the rest.
reap_backups() {
  local b keep=$((backup_keep)) list
  # `ls` exits non-zero (and, under pipefail, would fail the pipeline) when there
  # are no backups yet — capture first so a no-match is a clean no-op.
  list="$(ls -1t "${bin}".bak-* 2>/dev/null || true)"
  [ -n "$list" ] || return 0
  # Newest first by mtime; drop everything past the keep count.
  printf '%s\n' "$list" | tail -n "+$((keep + 1))" | while IFS= read -r b; do
    [ -n "$b" ] && rm -f "$b" && log "reaped old backup $(basename "$b")"
  done
  return 0
}

# Drift alarm (#872). The installer at $install_self is a HAND-PLACED copy of
# scripts/broker/idss-broker-install.sh — the broker rail deploys a *binary* from
# CI, but NOTHING re-places or checks the script that installs it, so a fix to the
# installer can drift arbitrarily far from what CI publishes with no signal. That
# is the same silent-undeployable-component shape as GOTCHAS #90 (wrong-mesh
# runner) and #91 (SIGPIPE marker check): a deploy path with a component in it
# that nothing deploys. publish-broker now uploads this script alongside the
# binary under each sha; here we REFUSE to install through a drifted installer —
# fetch the installer CI published for THIS sha, and if the on-disk copy differs,
# die loud so `deploy-broker` reds. A human then re-places the installer (see
# broker/README.md "Droplet one-time setup") and re-runs. Fixing the drift is not
# automated on purpose (a self-re-execing installer could break its own
# successor — #872's option 1, deferred to a human ruling); this makes the drift
# impossible to miss, which is the acceptance: an installer change either reaches
# the droplet or turns something red. Skipped when there is nothing to compare:
# an ad-hoc run from a checkout (no $install_self on disk), or a sha that predates
# installer publishing (older rollback target — the registry has no script to
# compare, so proceed rather than red a legitimate rollback).
assert_installer_not_drifted() {
  local sha="$1"
  [ -r "$install_self" ] || { log "no on-disk installer at $install_self — ad-hoc run, skipping drift check"; return 0; }
  local url="$server/api/packages/$owner/generic/$package/$sha/idss-broker-install.sh"
  local tmp; tmp="$(mktemp)"
  # shellcheck disable=SC2064
  trap "rm -f '$tmp'" RETURN
  if ! curl -fsSL --max-time 60 "${auth[@]}" -o "$tmp" "$url" 2>/dev/null || [ ! -s "$tmp" ]; then
    log "no published installer for ${sha:0:12} — sha predates installer publishing; skipping drift check"
    return 0
  fi
  cmp -s "$tmp" "$install_self" \
    || die "installer DRIFT (#872): $install_self differs from the idss-broker-install.sh CI published for ${sha:0:12}. The droplet's hand-placed installer is stale — re-place it (broker/README.md 'Droplet one-time setup') and re-run. Refusing to deploy through a drifted installer."
  log "installer matches the published copy for ${sha:0:12} — no drift"
}

main() {
  local sha="${1:-}"
  [ -n "$sha" ] || die "usage: idss-broker-install <fullsha>"
  # A 40-hex git sha — refuse anything else so a typo can't become a registry path.
  [[ "$sha" =~ ^[0-9a-f]{40}$ ]] || die "not a full git sha: '$sha'"

  # Refuse to deploy through a drifted installer BEFORE any binary work (#872).
  assert_installer_not_drifted "$sha"

  # Idempotent: the requested sha is already installed AND live -> nothing to do.
  if [ "$(installed_sha)" = "$sha" ] && broker_live; then
    log "sha ${sha:0:12} already installed and live — nothing to do"
    return 0
  fi

  # 1. Download the per-sha binary from the generic package registry (anon read).
  local url="$server/api/packages/$owner/generic/$package/$sha/ourcloud-broker-$arch"
  local tmp; tmp="$(mktemp)"
  # shellcheck disable=SC2064
  trap "rm -f '$tmp'" RETURN
  log "downloading ${package}@${sha:0:12} from $url"
  curl -fsSL --max-time 120 "${auth[@]}" -o "$tmp" "$url" \
    || die "download failed for ${sha:0:12} — is the sha published? (broker-deploy runs only after CI publishes)"

  # 2. Sanity-check: non-empty AND carries the version marker (not a 404 page).
  [ -s "$tmp" ] || die "downloaded binary is empty — refusing to install"
  # NOT `| grep -qF`: `grep -q` exits at the FIRST match, `strings` then dies of
  # SIGPIPE writing the rest of a ~9MB binary, and `set -o pipefail` (line 42)
  # reports the pipeline as 141 — so a GENUINE broker was rejected as "not a
  # broker artifact". That false negative is why this rail installed exactly
  # once in 11,639 Forgejo tasks; it is timing-dependent, so a small fake binary
  # (the offline test's) finishes writing first and never reproduces it.
  # GOTCHAS #91. Dropping -q makes grep drain the whole stream: no early exit,
  # no SIGPIPE, and the check is deterministic on any binary size.
  strings "$tmp" | grep -F "$marker" >/dev/null \
    || die "downloaded binary does not carry the '$marker' version marker — refusing to install a non-broker artifact"
  chmod 0755 "$tmp"

  # 3. Back up the running binary as .bak-<oldsha> before the swap.
  local oldsha; oldsha="$(installed_sha)"; [ -n "$oldsha" ] || oldsha="unknown"
  local backup=""
  if [ -e "$bin" ]; then
    backup="${bin}.bak-${oldsha}"
    cp -a "$bin" "$backup"
    log "backed up running binary -> $(basename "$backup")"
  fi

  # 4. Atomic swap + record the sha.
  install -m0755 "$tmp" "$bin"
  printf '%s\n' "$sha" > "$sha_file"
  stamp_build "$sha"
  log "installed ${sha:0:12} -> $bin; restarting $service"

  # 5. Restart and prove it came up.
  systemctl restart "$service" || log "systemctl restart returned non-zero — checking liveness anyway"
  if wait_live; then
    log "broker booted — ${sha:0:12} is live (is-active + offer 200)"
    reap_backups
    return 0
  fi

  # 6. Roll back to the backup and fail loud — journalctl keeps the OLD version.
  log "new binary ${sha:0:12} did not come up within ${health_timeout}s — rolling back"
  if [ -n "$backup" ] && [ -e "$backup" ]; then
    # install, not cp: cp opens the RUNNING binary for writing and dies with
    # "Text file busy" (ETXTBSY), aborting the rollback half-done; install
    # replaces the path the same way the forward swap in step 4 does.
    install -m0755 "$backup" "$bin"
    printf '%s\n' "$oldsha" > "$sha_file"
    stamp_build "$oldsha"
    systemctl restart "$service" || true
    log "restored $(basename "$backup") and restarted $service"
  else
    log "no backup to restore (was there a running broker before?) — leaving $service as-is"
  fi
  die "install of ${sha:0:12} failed and was rolled back"
}

main "$@"
