#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DRY_RUN=false

if [ "${1:-}" = "--dry-run" ]; then
    DRY_RUN=true
fi

run_step() {
    local label="$1"
    shift

    printf '\n== %s ==\n' "$label"
    printf '+ %s\n' "$*"
    if [ "$DRY_RUN" = "true" ]; then
        return 0
    fi
    "$@"
}

run_optional() {
    local label="$1"
    shift

    if ! run_step "$label" "$@"; then
        printf 'warn: step failed: %s\n' "$label" >&2
    fi
}

cat <<EOF
Power-loss recovery order
=========================

This sequence restores dependencies before dependents:
Debian runtime -> Gitea -> RPi DNS -> Pimox workers -> Kubernetes -> GitOps/apps -> edge/public URLs.
EOF

run_optional "Debian runtime status" systemctl is-active docker containerd
run_optional "Start Docker runtime" sudo systemctl start docker containerd
run_optional "Deploy or verify Gitea" "${REPO_ROOT}/jeannie" deploy-gitea
run_optional "Verify RPi services" "${REPO_ROOT}/jeannie" doctor-rpi
run_optional "Start Kubernetes cluster" "${REPO_ROOT}/jeannie" start-cluster
run_optional "Cluster doctor" "${REPO_ROOT}/jeannie" doctor-cluster
run_optional "GitOps status" "${REPO_ROOT}/jeannie" gitops-status
run_optional "Public edge doctor" "${REPO_ROOT}/jeannie" doctor-edge
run_optional "Final status cascade" "${REPO_ROOT}/jeannie" status

printf '\nRecovery sequence complete%s.\n' "$([ "$DRY_RUN" = "true" ] && printf ' dry-run' || true)"
