#!/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
#   SANDO_TOPOLOGY          /etc/sando/sando.toml        topology installed from the repo (see "Topology" below)
#
# Source: build from the LOCAL bare repo sandod already maintains
# (/srv/sando/mnw.git), not a remote fetch. 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.
#
# sandod fetches the deploy branch from the canonical remote into that bare repo
# at the top of its /self-update handler, so a sha pushed minutes ago is present
# here. It used to be reachable only if a *server* build had fetched since, which
# chained the controller's currency to the server's release cadence: shipping a
# controller fix meant cutting a server release first, and was impossible at all
# while the server was red. sandod remains the only writer of that repo, so the
# provenance seal below is unchanged.
#
# 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.
#
# Topology: this unit also INSTALLS `sando/sando.toml` from the checked-out sha
# over $SANDO_TOPOLOGY. The topology is not host-specific — it names tiers,
# nodes, gates and companions, and every one of those is a property of the
# deploy plan rather than of the box sandod happens to run on. It used to be
# hand-maintained, and the repo copy read as a source of truth that was
# deployed nowhere: the multithreaded companion block drifted for 19 days and
# was found by accident while diffing before an unrelated edit. Shipping it
# here makes the repo copy the deployed copy, which is the only arrangement
# where "edit the repo" and "change what sandod reads" are the same act.
#
# sandod cannot do this itself for the same reason it cannot install its own
# binary — and doing it from inside the daemon would be a bootstrap loop anyway,
# since the config being replaced is the one it is running on. The host-specific
# half stays where it was: $SANDO_DAEMON_CONFIG (bind address, tokens, database
# URL) is NOT installed from the repo, and `deploy/sando-daemon.toml.example` is
# still a template rather than a deployable file.
#
# The install lands BEFORE the --check-config self-test on purpose, so the test
# validates the new binary against the new topology — the pair that will
# actually boot. A failed test restores the previous topology before exiting, so
# a refused self-update leaves the box exactly as it found it.
#
# 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}"
TOPOLOGY="${SANDO_TOPOLOGY:-/etc/sando/sando.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; }

# Install the topology from the checked-out sha. This is what makes the repo copy
# the deployed copy; see "Topology" in the header. The daemon config beside it is
# host-specific and deliberately untouched.
#
# The previous copy is kept as a timestamped .bak so a bad topology is one `cp`
# away from being undone by hand, matching what the box already accumulates for
# every other file in /etc/sando. It is also what the self-test failure path
# below restores from.
NEW_TOPOLOGY="$REPO_DIR/sando/sando.toml"
[[ -f "$NEW_TOPOLOGY" ]] || { echo "sando-self-update: no topology at $NEW_TOPOLOGY in sha $SHA" >&2; exit 6; }
TOPOLOGY_BACKUP=""
if [[ -f "$TOPOLOGY" ]]; then
    if cmp -s "$NEW_TOPOLOGY" "$TOPOLOGY"; then
        echo "sando-self-update: topology unchanged"
    else
        TOPOLOGY_BACKUP="$TOPOLOGY.bak-$(date -u +%Y%m%dT%H%M%SZ)"
        cp -p "$TOPOLOGY" "$TOPOLOGY_BACKUP"
        echo "sando-self-update: topology differs; previous copy saved to $TOPOLOGY_BACKUP"
        diff -u "$TOPOLOGY_BACKUP" "$NEW_TOPOLOGY" || true
    fi
fi
install -m 0644 "$NEW_TOPOLOGY" "$TOPOLOGY"

# Restore the previous topology on any failure from here to the restart. Without
# this, a refused self-update would leave the new topology in place under the old
# binary: sandod keeps running on what it parsed at boot, so the mismatch would
# surface at the next unrelated restart rather than here, which is the worst of
# both files.
restore_topology() {
    if [[ -n "$TOPOLOGY_BACKUP" && -f "$TOPOLOGY_BACKUP" ]]; then
        install -m 0644 "$TOPOLOGY_BACKUP" "$TOPOLOGY"
        echo "sando-self-update: restored the previous topology from $TOPOLOGY_BACKUP" >&2
    fi
}

# 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.
#
# Since the topology was installed above, this now tests the pair: a topology the
# new binary cannot parse fails here too, and both halves are rolled back.
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
    restore_topology
    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"
if ! systemctl restart sandod; then
    echo "sando-self-update: sandod failed to restart on the new binary + topology" >&2
    restore_topology
    exit 7
fi
echo "sando-self-update: done ($SHA live)"
