#!/bin/bash
# rollback: point the live `sm` back at the release that was live before the last promote. Atomic; run it again to go forward.
#   bin/rollback --to RELEASE_ID     switch to releases/RELEASE_ID instead of the previous release (the live one becomes previous)
#   bin/rollback --force-during-run  switch although an admission or release step is running (its next command runs the other code)
#   Before anything moves, the target release must start: `self config` with its own config must report the plugin loaded.
set -u
stable="${SM_STABLE:-$HOME/Code/steuermaschine-stable}"
force=0; to=""; want_to=0
for a in "$@"; do
  if [ "$want_to" = 1 ]; then to="$a"; want_to=0; continue; fi
  case "$a" in -h|--help) sed -n '2,5p' "$0"; exit 0 ;; --force-during-run) force=1 ;; --to) want_to=1 ;; *) echo "rollback: unknown argument $a" >&2; exit 2 ;; esac
done
[ "$want_to" = 0 ] || { echo "rollback: --to takes a release id (a directory name under $stable/releases)" >&2; exit 2; }
if [ -n "$to" ]; then
  [[ "$to" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || { echo "rollback: --to $to is not a release id" >&2; exit 2; }
  [ -d "$stable/releases/$to" ] || { echo "rollback: no release $to in $stable/releases; nothing switched" >&2; exit 1; }
  target="releases/$to"
else
  [ -L "$stable/previous" ] || { echo "rollback: no previous release in $stable" >&2; exit 1; }
  target="$(readlink "$stable/previous")"
fi
# shellcheck source=bin/promote_lib.sh
. "$(cd "$(dirname "$0")" && pwd)/promote_lib.sh"
cur_rel="$(cd "$stable/current" && pwd -P)"; prev_rel="$(cd "$stable/$target" 2>/dev/null && pwd -P)" || { echo "rollback: $target is unreadable; nothing switched" >&2; exit 1; }
[ "$prev_rel" != "$cur_rel" ] || { echo "rollback: $target is already live; nothing switched" >&2; exit 1; }
# Start check: the release that becomes live must start with its own code and config before any state moves.
started="$(STEUERMASCHINE_PINNED="$prev_rel" STEUERMASCHINE_USER_CONFIG="$prev_rel/user-config.toml" "$prev_rel/venv/bin/steuermaschine" --format json self config 2>/dev/null)"
case "$started" in *'"plugin_loaded": true'*) ;; *) echo "rollback: $target does not start (self config does not report its plugin loaded); nothing switched" >&2; exit 1 ;; esac
# The state files move to the names the target release uses, while no write step runs (as promote does).
mark_switch_pending || echo "rollback: (the switch-pending file could not be written)" >&2
trap clear_switch_pending EXIT
if [ "$force" = 0 ]; then
  wait_idle 1800 15 >/dev/null || { echo "rollback: an admission or release step still runs after 30 min; nothing switched (or: bin/rollback --force-during-run)" >&2; exit 1; }
fi
migrate_state_to "$prev_rel/venv/bin/steuermaschine" "$prev_rel/user-config.toml" "$cur_rel/venv/bin/steuermaschine" "$cur_rel/user-config.toml" 2>&1 | sed 's/^/rollback:   /' >&2
[ "${PIPESTATUS[0]}" = 0 ] || { echo "rollback: the state could not be moved back; nothing switched" >&2; exit 1; }
python3 - "$stable" "$target" <<'PY'
import os, sys
stable, prev = sys.argv[1], sys.argv[2]
cur = os.readlink(os.path.join(stable, "current"))
for name, target in (("current", prev), ("previous", cur)):
    tmp = os.path.join(stable, f".{name}.{os.getpid()}")
    os.symlink(target, tmp)
    os.replace(tmp, os.path.join(stable, name))
print(f"rollback: live is now {prev} (was {cur})", file=sys.stderr)
PY
"$stable/bin/sm" self config | head -1
