#!/usr/bin/env bash
# Post-deploy e2e verdict handler (M24-9): the promote-on-pass / 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).
#
# 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 promote/rollback
#                                                 (e2e verdicts still red/green the run).
#   E2E_OUTCOME=pass                           -> exedev.sh MODE=promote: mark the running compose
#                                                 image as last e2e-green (the rollback target).
#                                                 Compose bookkeeping stays the promote target
#                                                 until the cutover retires the compose path
#                                                 (docs/deployment.md cutover runbook, step 4);
#                                                 helm keeps its own revision history.
#   E2E_OUTCOME=fail + E2E_TRIGGER="Deploy (dev)"      -> exedev.sh MODE=rollback_green: roll the
#                                                 compose API back to the last e2e-green image.
#   E2E_OUTCOME=fail + E2E_TRIGGER="Deploy (dev, k3s)" -> helm-dev.sh MODE=rollback: roll the helm
#                                                 release back to its previous revision (helm's
#                                                 history replaces the .last_green_tag files).
#   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 actions themselves:
# DEPLOY_HOST + DEPLOY_SSH_KEY (promote + both rollbacks), REGISTRY_USER + REGISTRY_TOKEN
# (rollbacks only - 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' - promote/rollback is not armed; nothing to do."
  exit 0
fi

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

if [ "$outcome" = "pass" ]; then
  echo "==> e2e passed: promoting the running dev image to last e2e-green"
  MODE=promote bash "$script_dir/exedev.sh"
  exit 0
fi

case "$trigger" in
  "Deploy (dev)")
    echo "==> e2e failed after a compose API deploy: rolling back to the last e2e-green image"
    summary "### ⚠️ Auto-rollback: post-deploy e2e failed, rolling the dev API back to the last e2e-green image."
    MODE=rollback_green bash "$script_dir/exedev.sh"
    ;;
  "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
