#!/bin/bash
# silvershell-agent self-update helper. Runs as root from silvershell-agent-update.service,
# started by silvershell-agent-update.path when the unprivileged agent writes a request.
# Spec: SilverDESK docs/superpowers/specs/2026-10-02-agent-self-update-design.md §3.3.
# It only ever installs a signed silvershell-agent version from the SilverLABS repo, never
# an older one (except to roll back), and rolls back if the new agent isn't healthy.
set -u

PKG=silvershell-agent
REQ="${SSA_REQUEST:-/run/silvershell-agent/update-request.json}"
STATUS="${SSA_STATUS:-/run/silvershell-agent/status.json}"
# The result lives in a ROOT-owned directory (the service's StateDirectory=silvershell-agent-update,
# mode 0755): the agent can read it but cannot plant links there to redirect root's writes.
RESULT="${SSA_RESULT:-/var/lib/silvershell-agent-update/update-result.json}"
REPO_HOST="${SSA_REPO_HOST:-apt.silverlabs.uk}"
SOURCES_LIST="${SSA_SOURCES_LIST:-/etc/apt/sources.list.d/silverlabs.list}"
GATE_SECONDS="${SSA_GATE_SECONDS:-300}"
POLL_SECONDS="${SSA_POLL_SECONDS:-5}"
TMPDIR_="${SSA_TMPDIR:-/tmp}"
REQUEST_ID="unknown"

log() { echo "silvershell-agent-update: $*"; }

# Installing the package replaces this file while it runs, so run from a private copy.
if [ "${SSA_REEXEC:-}" != "1" ]; then
  copy="$(mktemp "$TMPDIR_/ssa-update-helper.XXXXXX")" || exit 1
  cp "$0" "$copy" && chmod 0700 "$copy"
  SSA_REEXEC=1 exec bash "$copy" "$@"
fi
trap 'rm -f "$0"' EXIT
log "running from temp copy $0"

norm() { printf '%s' "$1" | sed -E 's/(\.0+)+$//'; }
installed() { dpkg-query -W -f='${Version}' "$PKG" 2>/dev/null; }

write_result() { # outcome from to running reason
  local reason tmp dir
  # Keep the JSON single-line and valid: drop quotes, backslashes and every control character.
  reason="$(printf '%s' "$5" | tr '\n\t' '  ' | tr -d '"\\' | LC_ALL=C tr -d '\000-\037' | cut -c1-300)"
  dir="$(dirname "$RESULT")"
  mkdir -p "$dir"
  # Unpredictable name + rename over the target: never writes through a planted link.
  tmp="$(mktemp "$dir/.update-result.XXXXXX")" || { log "cannot create result file in $dir"; return 1; }
  printf '{"requestId":"%s","outcome":"%s","from":"%s","to":"%s","running":"%s","reason":"%s","at":"%s"}\n' \
    "$REQUEST_ID" "$1" "$2" "$3" "$4" "$reason" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$tmp"
  chmod 0644 "$tmp"
  mv -fT "$tmp" "$RESULT"
  log "result: $1 ($2 -> $3, running $4): $reason"
}

# Wait for a status.json written at/after $2 (epoch) that shows version $1 and a panel connection.
gate() {
  local want since deadline v
  want="$(norm "$1")"; since="$2"; deadline=$(( $(date +%s) + GATE_SECONDS ))
  while [ "$(date +%s)" -le "$deadline" ]; do
    # Regular files only: a link or FIFO planted by the agent must neither pass the gate nor hang it.
    if [ -f "$STATUS" ] && [ ! -L "$STATUS" ] && [ "$(stat -c %Y "$STATUS")" -ge "$since" ]; then
      v="$(sed -nE 's/.*"version"[[:space:]]*:[[:space:]]*"([0-9.]+)".*/\1/p' "$STATUS")"
      if [ "$(norm "$v")" = "$want" ] && grep -q '"panelConnected"[[:space:]]*:[[:space:]]*true' "$STATUS"; then
        return 0
      fi
    fi
    sleep "$POLL_SECONDS"
  done
  return 1
}

apt_install() { # version extra-flag
  local out rc
  # INSTALL LAW: never pull Recommends. The agent .deb Recommends docker-cli, and a plain install
  # once removed docker-ce on IONOS (2026-09-20, prod outage).
  out="$(DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=120 -o Dpkg::Options::=--force-confold \
        install -y --no-install-recommends $2 "$PKG=$1" 2>&1)"; rc=$?
  LAST_APT_LINE="$(printf '%s\n' "$out" | grep -v '^$' | tail -n 1)"
  return $rc
}

refresh_repo() {
  if [ -f "$SOURCES_LIST" ]; then
    apt-get -o Dir::Etc::sourcelist="$SOURCES_LIST" -o Dir::Etc::sourceparts=- -o APT::Get::List-Cleanup=0 update >/dev/null 2>&1
  else
    apt-get update >/dev/null 2>&1
  fi
}

# The agent controls this path: accept only a regular file (no link, FIFO or directory).
if [ -L "$REQ" ] || { [ -e "$REQ" ] && [ ! -f "$REQ" ]; }; then
  rm -rf "$REQ"
  FROM="$(installed)"
  write_result rejected "$FROM" "" "$FROM" "request is not a regular file"; exit 0
fi
[ -f "$REQ" ] || { log "no request"; exit 0; }
BODY="$(timeout 5 head -c 4096 "$REQ")"
rm -f "$REQ"
VERSION="$(printf '%s' "$BODY" | sed -nE 's/.*"version"[[:space:]]*:[[:space:]]*"([0-9]+(\.[0-9]+){1,3})".*/\1/p')"
RID="$(printf '%s' "$BODY" | sed -nE 's/.*"requestId"[[:space:]]*:[[:space:]]*"([0-9a-fA-F-]{36})".*/\1/p')"
[ -n "$RID" ] && REQUEST_ID="$RID"
FROM="$(installed)"

if [ -z "$VERSION" ] || [ -z "$RID" ]; then
  write_result rejected "$FROM" "" "$FROM" "malformed request"; exit 0
fi

refresh_repo
if ! apt-cache madison "$PKG" | awk -F'|' -v v="$VERSION" '{gsub(/ /,"",$2)} $2==v' | grep -q "$REPO_HOST"; then
  write_result rejected "$FROM" "$VERSION" "$FROM" "$VERSION not available from $REPO_HOST"; exit 0
fi
if ! dpkg --compare-versions "$VERSION" gt "$FROM"; then
  write_result rejected "$FROM" "$VERSION" "$FROM" "$VERSION is not newer than installed $FROM"; exit 0
fi
if apt-mark showhold | grep -qx "$PKG"; then
  write_result rejected "$FROM" "$VERSION" "$FROM" "$PKG is held"; exit 0
fi

rollback() { # why
  local since
  log "rolling back to $FROM: $1"
  since="$(date +%s)"
  if ! apt_install "$FROM" "--allow-downgrades"; then
    write_result failed "$FROM" "$VERSION" "$(installed)" "rollback failed: $LAST_APT_LINE (after: $1)"; exit 0
  fi
  if gate "$FROM" "$since"; then
    write_result rolled-back "$FROM" "$VERSION" "$(installed)" "$1; previous $FROM healthy"
  else
    write_result rolled-back "$FROM" "$VERSION" "$(installed)" "$1; previous $FROM NOT healthy"
  fi
  exit 0
}

log "upgrading $PKG $FROM -> $VERSION (request $REQUEST_ID)"
START="$(date +%s)"
if ! apt_install "$VERSION" "--only-upgrade"; then
  dpkg --configure -a >/dev/null 2>&1
  if ! apt_install "$VERSION" "--only-upgrade"; then
    # Nothing changed (dpkg lock busy, network error): the old agent is untouched, so this is a
    # retryable failure — never a rollback, which would hold the whole agent rollout.
    if [ "$(installed)" = "$FROM" ]; then
      write_result failed "$FROM" "$VERSION" "$FROM" "apt: $LAST_APT_LINE; nothing changed"; exit 0
    fi
    rollback "apt: $LAST_APT_LINE"
  fi
fi
if gate "$VERSION" "$START"; then
  write_result succeeded "$FROM" "$VERSION" "$(installed)" "healthy on $VERSION"
else
  rollback "$VERSION not healthy within ${GATE_SECONDS}s (no fresh connected status)"
fi
exit 0
