#!/usr/bin/env bash
# Fail when the live Sando topology is not what the repo says it should be.
#
# The self-update oneshot installs `sando/sando.toml` over /etc/sando/sando.toml,
# so between self-updates the two can still separate: a commit lands on main and
# nothing has shipped it yet, or somebody edits the live file by hand. Neither is
# visible without someone remembering to diff, which is exactly how the
# multithreaded companion block drifted for 19 days.
#
# This is the reporting half. It changes nothing; it exits non-zero and prints
# the diff. Run from `sando-config-drift.timer` daily, where a non-zero exit
# leaves a failed unit for PoM to see, or by hand on the Sando host.
#
# Source of truth is the deploy branch of the bare repo sandod maintains, NOT the
# operator's dev tree: an uncommitted edit in ~/Code is not deployable and should
# not read as drift, and the bare repo is the same provenance seal the
# self-update's ancestor check trusts.
#
# Config via environment (defaults shown):
#   SANDO_UPSTREAM_URL    /srv/sando/mnw.git      bare repo to read the topology from
#   SANDO_DEPLOY_BRANCH   main                    branch within it
#   SANDO_TOPOLOGY        /etc/sando/sando.toml   the live file
set -euo pipefail

BARE="${SANDO_UPSTREAM_URL:-/srv/sando/mnw.git}"
BRANCH="${SANDO_DEPLOY_BRANCH:-main}"
TOPOLOGY="${SANDO_TOPOLOGY:-/etc/sando/sando.toml}"

[[ -f "$TOPOLOGY" ]] || { echo "check-topology-drift: no live topology at $TOPOLOGY" >&2; exit 2; }

# No fetch. sandod is the only writer of this repo and refreshes it on every
# build and self-update; fetching here would need git credentials this unit
# deliberately does not carry, and a stale bare repo is the self-update's
# problem rather than a drift report's.
if ! REPO_COPY="$(git -C "$BARE" show "$BRANCH:sando/sando.toml" 2>/dev/null)"; then
    echo "check-topology-drift: cannot read $BRANCH:sando/sando.toml from $BARE" >&2
    exit 2
fi

if diff -u --label "$BARE ($BRANCH)" --label "$TOPOLOGY" <(printf '%s\n' "$REPO_COPY") "$TOPOLOGY"; then
    echo "check-topology-drift: live topology matches $BRANCH"
    exit 0
fi

cat >&2 <<'MSG'

check-topology-drift: the live topology and the repo have separated.

Fix it by shipping, not by editing the live file: push the intended topology to
main and trigger a sandod self-update, which installs it. Hand-editing
/etc/sando/sando.toml is what this check exists to catch.
MSG
exit 1
