#!/usr/bin/env bash
# Rebuild and restart sandod itself to a target commit.
#
# Runs as ROOT, invoked by the oneshot unit `sando-update@<sha>.service` (the
# sha is the instance name, passed here as $1). sandod cannot do this itself:
# it runs User=sando with NoNewPrivileges + ProtectSystem=strict, so it can
# neither write /usr/local/bin/sandod nor restart its own service. sandod only
# *triggers* this unit (authorized for the sando user by a scoped polkit rule);
# the actual privileged work lives here.
#
# Build runs as the unprivileged build user (the sando user already carries a
# rustup toolchain at /srv/sando/.cargo/bin); only the install + restart run as
# root. The build uses a dedicated checkout, never the operator's dev tree.
#
# Config via environment (defaults shown), set in the unit or /etc/sando/sando.env:
#   SANDO_SELF_UPDATE_DIR   /srv/sando/self-update       build checkout parent (build-user-owned)
#   SANDO_UPSTREAM_URL      /srv/sando/mnw.git           source repo (see "Source" below)
#   SANDO_BUILD_USER        sando
#   SANDO_BIN               /usr/local/bin/sandod        install destination
#   SANDO_DEPLOY_BRANCH     main                         the only branch a self-update sha may live on
#   SANDO_DAEMON_CONFIG     /etc/sando/sando-daemon.toml config the --check-config self-test loads
#
# Source: build from the LOCAL bare repo sandod already maintains
# (/srv/sando/mnw.git), not a remote fetch. The self-update sha is one that was
# already deployed as a server release, so `/rebuild` has force-updated
# refs/heads/main in the bare repo to include it — the sha and a current, trusted
# main are both present locally. Building from a remote (git@ssh.makenot.work)
# gave the `sando` user no git creds and broke the moment git hosting was down —
# it blocked the self-update during the 2026-07-09 deploy (postmortem #7). The
# local bare repo has no such external dependency.
#
# Provenance: sandod (bearer-gated) only *triggers* this unit with a hex sha; it
# does not prove the sha is a commit anyone intended to deploy. Without a check,
# the deploy token would be root code-exec on this host. So after fetch we REFUSE
# any sha that is not an ancestor of origin/$SANDO_DEPLOY_BRANCH: a feature-branch
# tip, an unknown sha, or a commit not on the deploy branch never reaches the
# build/install lines (exit 4). Only sandod writes the bare repo (fetching main
# from the authenticated upstream), so its main is a trustworthy provenance seal.
# A signed-tag check is the planned follow-up once release signing exists.
#
# Safety net: a clean build (no stale incremental cache) plus a --check-config
# self-test of the freshly built binary against the LIVE config gate the install.
# A stale incremental object once produced a sandod that could not parse its own
# node_health config and crash-looped (postmortem #6); either guard alone stops
# that binary from ever being installed.
set -euo pipefail

SHA="${1:-}"
if [[ ! "$SHA" =~ ^[0-9a-f]{7,40}$ ]]; then
    echo "sando-self-update: refusing non-hex sha: '$SHA'" >&2
    exit 2
fi

SELF_DIR="${SANDO_SELF_UPDATE_DIR:-/srv/sando/self-update}"
UPSTREAM_URL="${SANDO_UPSTREAM_URL:-/srv/sando/mnw.git}"
BUILD_USER="${SANDO_BUILD_USER:-sando}"
BIN="${SANDO_BIN:-/usr/local/bin/sandod}"
DEPLOY_BRANCH="${SANDO_DEPLOY_BRANCH:-main}"
DAEMON_CONFIG="${SANDO_DAEMON_CONFIG:-/etc/sando/sando-daemon.toml}"
REPO_DIR="$SELF_DIR/MNW"
BUILD_HOME="$(getent passwd "$BUILD_USER" | cut -d: -f6)"

echo "sando-self-update: building sandod @ $SHA as $BUILD_USER (provenance: origin/$DEPLOY_BRANCH)"

# Fetch + provenance check + checkout + build, all as the unprivileged build
# user. The clone is created once; thereafter we just fetch the new sha. Detached
# checkout so the dedicated tree never carries a branch to drift.
install -d -o "$BUILD_USER" -g "$BUILD_USER" "$SELF_DIR"
runuser -u "$BUILD_USER" -- env \
    HOME="$BUILD_HOME" \
    PATH="$BUILD_HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin" \
    bash -euo pipefail -c "
        if [[ ! -d '$REPO_DIR/.git' ]]; then
            git clone '$UPSTREAM_URL' '$REPO_DIR'
        fi
        cd '$REPO_DIR'
        # Pin origin to the configured source every run, so switching
        # SANDO_UPSTREAM_URL (e.g. remote -> local bare repo) takes effect on an
        # already-cloned checkout instead of silently keeping the old remote.
        git remote set-url origin '$UPSTREAM_URL'
        git fetch --prune origin
        # Provenance seal: the sha must be reachable from the deploy branch in the
        # source repo. --is-ancestor exits 1 for a non-ancestor and >1 for a
        # bad/unresolvable ref, so any non-deploy-branch sha is refused fail-closed
        # before a single line is built or installed.
        if ! git merge-base --is-ancestor '$SHA' 'origin/$DEPLOY_BRANCH'; then
            echo \"sando-self-update: refusing sha '$SHA' — not an ancestor of origin/$DEPLOY_BRANCH\" >&2
            exit 4
        fi
        git checkout --detach '$SHA'
        cd sando
        # Clean build: wipe the workspace target so no stale incremental object
        # survives across shas. A reused pre-node_health Gate enum object once
        # produced a sandod that crash-looped on the current config (postmortem
        # #6). Self-updates are rare, so a full recompile is a cheap insurance.
        cargo clean
        cargo build --release --locked -p sando-daemon
    "

# Workspace shares one target dir at sando/target; -p sando-daemon avoids
# compiling the TUI on the build host.
NEW_BIN="$REPO_DIR/sando/target/release/sandod"
[[ -x "$NEW_BIN" ]] || { echo "sando-self-update: build produced no binary at $NEW_BIN" >&2; exit 3; }

# Self-test the fresh binary against the LIVE config BEFORE the swap: prove it can
# load + parse the exact daemon config + topology sandod will boot against. Run as
# the build user (not root) so the readability check matches the running daemon's
# identity. A binary that can't parse the current config (the postmortem #6
# brick) fails here and is never installed — sandod keeps running on the old one.
echo "sando-self-update: self-testing $NEW_BIN against $DAEMON_CONFIG"
if ! runuser -u "$BUILD_USER" -- env SANDO_CONFIG="$DAEMON_CONFIG" "$NEW_BIN" --check-config; then
    echo "sando-self-update: new binary FAILED --check-config against $DAEMON_CONFIG; refusing to install (sandod left running on the current binary)" >&2
    exit 5
fi

# Install + restart as root. install is atomic (writes a temp then renames), so
# a concurrent exec of $BIN never sees a half-written file.
echo "sando-self-update: installing $NEW_BIN -> $BIN and restarting sandod"
install -m 0755 "$NEW_BIN" "$BIN"
systemctl restart sandod
echo "sando-self-update: done ($SHA live)"
