#!/usr/bin/env bash
# Post-deploy e2e verdict handler (M24-9): the auto-rollback-on-failure branch of the
# post-deploy E2E workflows (e2e-post-deploy.yml, called by E2E (dev) / E2E (staging)),
# factored out of the workflow YAML so the decision matrix is unit-testable offline
# (scripts/deploy/tests/test_e2e_promote_rollback.sh - stubbed ssh, no live deploy).
#
# The compose deploy path was retired post-cutover (docs/deployment.md cutover runbook,
# step 4), and with it the promote-on-pass bookkeeping: helm keeps its own revision
# history, so a pass verdict needs no action at all.
#
# Decision matrix (validated inputs first - no SSH happens on a rejected or no-op invocation):
#   E2E_ENV=staging                            -> no-op: staging has no deploy target until M25
#                                                 stands one up; extend this script then.
#   DEPLOY_HOST unset/empty                    -> no-op: the env is not armed for rollback
#                                                 (e2e verdicts still red/green the run).
#   E2E_OUTCOME=pass                           -> no-op: helm's revision history is the
#                                                 rollback target; nothing to record.
#   E2E_OUTCOME=fail + E2E_TRIGGER="Deploy (dev, k3s)" -> helm-dev.sh MODE=rollback: roll the helm
#                                                 release back to its previous revision.
#   E2E_OUTCOME=fail + any other/empty trigger -> no-op: a web deploy or manual-dispatch failure
#                                                 is not fixed by an API rollback.
#
# Requires: E2E_OUTCOME (pass|fail), E2E_ENV (dev|staging). For the rollback itself:
# DEPLOY_HOST + DEPLOY_SSH_KEY, REGISTRY_USER + REGISTRY_TOKEN (re-pulling an evicted image
# needs a registry credential). Optional: E2E_TRIGGER (the completed deploy workflow's name;
# empty for a manual dispatch). Run from the repo root.
set -euo pipefail

outcome="${E2E_OUTCOME:?E2E_OUTCOME not set (pass|fail - the e2e suite verdict)}"
env_name="${E2E_ENV:?E2E_ENV not set (dev|staging - the environment the suite ran against)}"
trigger="${E2E_TRIGGER:-}"

case "$outcome" in
  pass | fail) ;;
  *) echo "::error::E2E_OUTCOME must be pass|fail (got '$outcome')" >&2; exit 1 ;;
esac
case "$env_name" in
  dev | staging) ;;
  *) echo "::error::E2E_ENV must be dev|staging (got '$env_name')" >&2; exit 1 ;;
esac

summary() { # append a line to the Actions run summary (no-op outside Actions)
  [ -z "${GITHUB_STEP_SUMMARY:-}" ] || echo "$1" >> "$GITHUB_STEP_SUMMARY"
}

if [ "$env_name" = "staging" ]; then
  echo "staging has no deploy target yet (the M25 cluster bring-up ships it) -" \
    "promote/rollback is deferred; nothing to do."
  exit 0
fi
if [ -z "${DEPLOY_HOST:-}" ]; then
  echo "no DEPLOY_HOST configured for '$env_name' - rollback is not armed; nothing to do."
  exit 0
fi

script_dir="$(dirname "${BASH_SOURCE[0]}")"

if [ "$outcome" = "pass" ]; then
  echo "e2e passed - helm's revision history is the rollback target; nothing to record."
  exit 0
fi

case "$trigger" in
  "Deploy (dev, k3s)")
    echo "==> e2e failed after a k3s helm deploy: rolling back to the previous helm revision"
    summary "### ⚠️ Auto-rollback: post-deploy e2e failed, rolling the dev helm release back to its previous revision."
    MODE=rollback bash "$script_dir/helm-dev.sh"
    ;;
  *)
    echo "e2e failed, but the trigger ('${trigger:-manual dispatch}') is not an API deploy -" \
      "an API rollback would not fix it; nothing to do."
    ;;
esac
