#!/usr/bin/env bash
# =============================================================================
# WPCloudOps - Authenticated Bootstrap Installer
# WPCloudOps™ Enterprise Engine Installer (WP CloudOps)
# Milestone: Unified Installer & Release Engine Architecture
# =============================================================================
# Dual-Mode Operational Pipeline:
#   1. Remote Bootstrap Mode (executed via curl / get.wpcloudops.com):
#        curl -fsSL https://get.wpcloudops.com | sudo bash
#        cat /run/secrets/wpco_key | sudo bash wpcloudops-install.sh
#   2. Local Package Verification Mode (executed with release artifacts):
#        wpcloudops-install.sh --manifest <PATH> --signature <PATH> --payload <PATH>
# =============================================================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd -P)"

# -----------------------------------------------------------------------------
# Mode Detection: Remote Bootstrap vs Local Package Verification
# -----------------------------------------------------------------------------
IS_LOCAL_VERIFY_MODE="false"
for arg in "$@"; do
  if [[ "$arg" == "--manifest" || "$arg" == "--manifest="* ]]; then
    IS_LOCAL_VERIFY_MODE="true"
    break
  fi
done

# -----------------------------------------------------------------------------
# Terminal Capability & Styling
# -----------------------------------------------------------------------------
IS_TTY="false"
if [[ -t 1 || -t 2 ]]; then
  IS_TTY="true"
fi

if [[ "$IS_TTY" == "true" ]]; then
  BOLD="\033[1m"
  CYAN="\033[0;36m"
  GREEN="\033[0;32m"
  YELLOW="\033[0;33m"
  RED="\033[0;31m"
  BLUE="\033[0;34m"
  RESET="\033[0m"
else
  BOLD=""
  CYAN=""
  GREEN=""
  YELLOW=""
  RED=""
  BLUE=""
  RESET=""
fi

# -----------------------------------------------------------------------------
# Cursor Restoration & Cleanup Trap
# -----------------------------------------------------------------------------
# shellcheck disable=SC2329
cleanup_bootstrap() {
  local exit_code=$?
  if [[ "$IS_TTY" == "true" ]]; then
    printf '\e[?25h' >&2 2>/dev/null || true
  fi
  if [[ -n "${STAGING_DIR:-}" && -d "${STAGING_DIR:-}" ]]; then
    rm -rf "$STAGING_DIR" 2>/dev/null || true
  fi
  if [[ -n "${AUTH_RESP_TMP:-}" && -f "${AUTH_RESP_TMP:-}" ]]; then
    rm -f "$AUTH_RESP_TMP" 2>/dev/null || true
  fi
  exit "$exit_code"
}
trap cleanup_bootstrap EXIT INT TERM

# -----------------------------------------------------------------------------
# Self-Contained UX & Diagnostic Helpers
# -----------------------------------------------------------------------------
print_adaptive_header() {
  if [[ "$IS_TTY" == "true" ]]; then
    cat <<EOF >&2
${CYAN}╭──────────────────────────────────────────────────────────╮
│   ${BOLD}☁  WP CloudOps™ Cloud-Native WordPress Infrastructure${RESET}${CYAN}  │
│      Authenticated Zero-Trust Release Pipeline           │
│      https://wpcloudops.com • Canonical: /opt/wpcloudops │
╰──────────────────────────────────────────────────────────╯${RESET}
EOF
  else
    cat <<'EOF' >&2
=============================================================
  WP CloudOps™ Cloud-Native WordPress Infrastructure
  Authenticated Zero-Trust Release Pipeline
  https://wpcloudops.com • Canonical: /opt/wpcloudops
=============================================================
EOF
  fi
}

# shellcheck disable=SC2329
run_with_cloud_pulse() {
  local desc="$1"
  shift

  if [[ "$IS_TTY" != "true" ]]; then
    printf '[INFO] %s...\n' "$desc" >&2
    local rc=0
    "$@" || rc=$?
    if [[ $rc -eq 0 ]]; then
      printf '[INFO] %s: done\n' "$desc" >&2
    else
      printf '[CRITICAL] %s failed (exit %d)\n' "$desc" "$rc" >&2
    fi
    return $rc
  fi

  local glyphs=('☁ ⇡' '☁ ⇢' '☁ ⇣' '☁ ⇠' '☁ ⚡')
  local num_glyphs=${#glyphs[@]}
  local start_time
  start_time=$(date +%s)

  printf '\e[?25l' >&2

  local tmp_out
  tmp_out=$(mktemp "/tmp/wpco_spin.XXXXXX" 2>/dev/null || true)

  if [[ -n "$tmp_out" ]]; then
    "$@" > "$tmp_out" 2>&1 &
  else
    "$@" >/dev/null 2>&1 &
  fi
  local cmd_pid=$!

  local i=0
  while kill -0 "$cmd_pid" 2>/dev/null; do
    local now
    now=$(date +%s)
    local elapsed=$((now - start_time))
    local glyph="${glyphs[$((i % num_glyphs))]}"
    printf "\r\e[2K  ${BOLD}${CYAN}%s${RESET} %s ${BLUE}(%02ds)${RESET} " "$glyph" "$desc" "$elapsed" >&2
    i=$((i + 1))
    sleep 0.1
  done

  local rc=0
  wait "$cmd_pid" || rc=$?

  printf '\e[?25h' >&2

  local total_elapsed
  total_elapsed=$(($(date +%s) - start_time))
  if [[ $rc -eq 0 ]]; then
    printf "\r\e[2K  ${GREEN}✓${RESET} %s ${GREEN}(%02ds)${RESET}\n" "$desc" "$total_elapsed" >&2
    if [[ -n "$tmp_out" && -f "$tmp_out" ]]; then
      rm -f "$tmp_out" 2>/dev/null || true
    fi
    return 0
  else
    printf "\r\e[2K  ${RED}✗${RESET} ${BOLD}%s failed${RESET} ${RED}(%02ds • exit %d)${RESET}\n" "$desc" "$total_elapsed" "$rc" >&2
    if [[ -n "$tmp_out" && -s "$tmp_out" ]]; then
      cat "$tmp_out" >&2
      rm -f "$tmp_out" 2>/dev/null || true
    fi
    return $rc
  fi
}

check_binary_shadowing() {
  local cmd_name="$1"
  local target_path="$2"

  local active_bin
  active_bin=$(command -v "$cmd_name" 2>/dev/null || true)

  if [[ -z "$active_bin" ]]; then
    if [[ ":$PATH:" != *":/usr/local/bin:"* ]]; then
      if [[ "$IS_TTY" == "true" ]]; then
        printf '\n%b┌─ WP CloudOps PATH Diagnostic ─────────────────────────────┐\n' "$YELLOW" >&2
        printf "│ ⚠ NOTICE: '%s' is installed at %s,\n" "$cmd_name" "$target_path" >&2
        printf "│   but /usr/local/bin is missing from your PATH.          │\n" >&2
        printf "│                                                          │\n" >&2
        printf '│ Recommended action:                                      │\n' >&2
        printf '│   export PATH="/usr/local/bin:$%s"                    │\n' "PATH" >&2
        printf '└──────────────────────────────────────────────────────────┘%b\n\n' "$RESET" >&2
      else
        printf '[WARN] %s installed at %s but /usr/local/bin is not in PATH. Run: export PATH="/usr/local/bin:$%s"\n' "$cmd_name" "$target_path" "PATH" >&2
      fi
    fi
    return 0
  fi

  local resolved_active resolved_target
  resolved_active=$(readlink -f "$active_bin" 2>/dev/null || true)
  resolved_target=$(readlink -f "$target_path" 2>/dev/null || true)

  if [[ "$active_bin" != "$target_path" && ( -z "$resolved_active" || "$resolved_active" != "$resolved_target" ) ]]; then
    if [[ "$IS_TTY" == "true" ]]; then
      printf '\n%b┌─ WP CloudOps PATH Diagnostic ─────────────────────────────┐\n' "$YELLOW" >&2
      printf "│ ⚠ NOTICE: Another binary '%s' exists at:         │\n" "$cmd_name" >&2
      printf "│   %-54s │\n" "$active_bin" >&2
      printf "│ Target installation is linked at:                        │\n" >&2
      printf "│   %-54s │\n" "$target_path" >&2
      printf "│                                                          │\n" >&2
      printf "│ Recommended action:                                      │\n" >&2
      printf "│   sudo rm -f %-43s │\n" "$active_bin" >&2
      printf '└──────────────────────────────────────────────────────────┘%b\n\n' "$RESET" >&2
    else
      printf '[WARN] Another binary for %s exists at %s, which shadows %s. Consider removing %s.\n' "$cmd_name" "$active_bin" "$target_path" "$active_bin" >&2
    fi
  fi
}

print_completion_card() {
  local version="$1"
  local install_root="$2"
  local license_url="$3"

  if [[ "$IS_TTY" == "true" ]]; then
    cat <<EOF

${GREEN}=============================================================${RESET}
  ${BOLD}${CYAN}☁  WP CloudOps Engine v${version} is Live!${RESET}
${GREEN}=============================================================${RESET}
  ${BOLD}Canonical CLI${RESET} : wpcloudops
  ${BOLD}Fast Alias${RESET}    : wpco
  ${BOLD}Active Target${RESET} : ${install_root}/current
  ${BOLD}Control Plane${RESET} : ${license_url}
  ${BOLD}Documentation${RESET} : https://wpcloudops.com/docs

  ${BOLD}Next Steps:${RESET}
    • Run setup wizard : ${CYAN}sudo wpcloudops --site example.com${RESET}
    • Check status     : ${CYAN}sudo wpco --license-status${RESET}
${GREEN}=============================================================${RESET}

EOF
  else
    cat <<EOF

=============================================================
  ☁  WP CloudOps Engine v${version} is Live!
=============================================================
  Canonical CLI : wpcloudops
  Fast Alias    : wpco
  Active Target : ${install_root}/current
  Control Plane : ${license_url}
  Documentation : https://wpcloudops.com/docs

  Next Steps:
    • Run setup wizard : sudo wpcloudops --site example.com
    • Check status     : sudo wpco --license-status
=============================================================

EOF
  fi
}

scan_and_diagnose_failure() {
  local error_output="$1"
  local rc="${2:-1}"

  if [[ -t 1 || -t 2 ]]; then
    printf "\n\033[0;31m┌─ WP CloudOps Diagnostic Assistant ───────────────────────┐\033[0m\n" >&2
    printf "\033[0;31m│ Step exit status: %-38s │\033[0m\n" "$rc" >&2
    if [[ "$error_output" =~ "Text file busy" || "$error_output" =~ "ETXTBSY" || "$error_output" =~ "EEXIST" ]]; then
      printf "\033[0;31m│ Cause: File system lock or running process active.        │\033[0m\n" >&2
      printf "│ Action: Active processes may be holding execution locks. │\n" >&2
      if command -v fuser >/dev/null 2>&1; then
        local locked_pids
        locked_pids=$(fuser "/opt/wpcloudops/current" 2>/dev/null || true)
        if [[ -n "$locked_pids" ]]; then
          printf "│ Active PIDs: %-43s │\n" "$locked_pids" >&2
        fi
      fi
    elif [[ "$error_output" =~ "ETIMEDOUT" || "$error_output" =~ "Connection refused" || "$error_output" =~ "Could not resolve" ]]; then
      printf "\033[0;31m│ Cause: Network reachability / firewall egress issue.     │\033[0m\n" >&2
      printf "│ Action: Verify outbound HTTPS (port 443) connectivity     │\n" >&2
      printf "│         to control plane licensing endpoint.             │\n" >&2
    elif [[ "$error_output" =~ "ENOSPC" || "$error_output" =~ "No space left on device" ]]; then
      printf "\033[0;31m│ Cause: Storage disk exhaustion or inode saturation.       │\033[0m\n" >&2
      printf "│ Action: Check free space and inodes via: df -h /opt      │\n" >&2
    elif [[ "$error_output" =~ "minisign" || "$error_output" =~ "signature" || "$error_output" =~ "Trusted Comment" ]]; then
      printf "\033[0;31m│ Cause: Cryptographic trust verification failed.          │\033[0m\n" >&2
      printf "│ Action: Verify system clock synchronization (NTP). Stale  │\n" >&2
      printf "│         clock skew or untrusted RTA keys reject releases. │\n" >&2
    fi
    printf "\033[0;31m└──────────────────────────────────────────────────────────┘\033[0m\n\n" >&2
  fi
}

die() {
  printf '[CRITICAL] %s\n' "$*" >&2
  scan_and_diagnose_failure "$*" 1
  exit 1
}

info() {
  printf '[INFO] %s\n' "$*" >&2
}

warn() {
  printf '[WARN] %s\n' "$*" >&2
}

# -----------------------------------------------------------------------------
# REMOTE BOOTSTRAP WORKFLOW (MODE A)
# -----------------------------------------------------------------------------
run_remote_bootstrap() {
  # Quick help inspection before privilege gating
  for arg in "$@"; do
    if [[ "$arg" == "-h" || "$arg" == "--help" ]]; then
      cat <<'EOF' >&2
Usage: wpcloudops-install.sh [OPTIONS]

Remote Bootstrap Mode (Default / curl https://get.wpcloudops.com | sudo bash):
  --license-url URL        Licensing control-plane URL (default: https://license.wpcloudops.com)
  --install-root PATH      Installation root path (default: /opt/wpcloudops)
  --version VERSION        Target release version (default: latest active release)
  --channel CHANNEL        Release channel (stable|staging, default: stable)
  --allow-downgrade        Allow installation of lower release sequence
  --allow-unsupported-eol-os Allow install on unsupported or EOL OS platforms
  --skip-health-check      Skip post-installation health verification
  --dry-run                Verify authorization and release integrity without persisted install
  -h, --help               Show this help message

Authentication:
  Provide license key via WPCLOUDOPS_LICENSE_KEY environment variable, pipe
  via stdin (e.g. 'cat /run/secrets/wpco_key | sudo bash install.sh'), or enter via the secure
  hidden interactive prompt. Passing keys via CLI arguments is rejected to
  prevent exposure in process listings (/proc/<pid>/cmdline) and bash history.
EOF
      exit 0
    fi
  done

  if [[ "${WPCLOUDOPS_TEST_MODE:-false}" != "true" ]]; then
    [[ "${EUID:-$(id -u)}" -eq 0 ]] || die "Root privileges are required. Please run with sudo or as root."
  fi

  local curl_bin python_bin tar_bin gzip_bin
  curl_bin="$(command -v curl || true)"
  [[ -n "$curl_bin" && -x "$curl_bin" ]] || die "curl binary not found. Please install curl."

  python_bin="$(command -v python3 || true)"
  [[ -n "$python_bin" && -x "$python_bin" ]] || die "python3 binary not found. Please install python3."

  tar_bin="$(command -v tar || true)"
  [[ -n "$tar_bin" && -x "$tar_bin" ]] || die "tar binary not found."

  gzip_bin="$(command -v gzip || true)"
  [[ -n "$gzip_bin" && -x "$gzip_bin" ]] || die "gzip binary not found."

  local LICENSE_KEY="${WPCLOUDOPS_LICENSE_KEY:-}"
  unset WPCLOUDOPS_LICENSE_KEY
  local license_url="${WPCLOUDOPS_LICENSE_URL:-https://staging-license.wpcloudops.com}"
  local install_root_dir="${WPCLOUDOPS_INSTALL_ROOT:-/opt/wpcloudops}"
  local target_version="${WPCLOUDOPS_RELEASE_VERSION:-}"
  local release_channel="${WPCLOUDOPS_RELEASE_CHANNEL:-}"
  local dry_run_mode="false"
  local allow_downgrade_mode="false"
  local allow_unsupported_eol_os_mode="false"
  local skip_health_check_mode="false"

  while (($#)); do
    case "$1" in
      --license-key|--license-key=*)
        die "Passing --license-key on argv is disabled for security. Use WPCLOUDOPS_LICENSE_KEY environment variable, pipe via stdin, or enter at the secure prompt."
        ;;
      --license-url|--install-root|--version|--channel)
        (($# >= 2)) || die "$1 requires an argument"
        local opt_key="$1" opt_val="$2"; shift 2
        case "$opt_key" in
          --license-url) license_url="$opt_val" ;;
          --install-root) install_root_dir="$opt_val" ;;
          --version) target_version="$opt_val" ;;
          --channel) release_channel="$opt_val" ;;
        esac
        ;;
      --license-url=*) [[ -z "${1#*=}" ]] && die "--license-url requires a non-empty value"; license_url="${1#*=}"; shift ;;
      --install-root=*) [[ -z "${1#*=}" ]] && die "--install-root requires a non-empty value"; install_root_dir="${1#*=}"; shift ;;
      --version=*) [[ -z "${1#*=}" ]] && die "--version requires a non-empty value"; target_version="${1#*=}"; shift ;;
      --channel=*) [[ -z "${1#*=}" ]] && die "--channel requires a non-empty value"; release_channel="${1#*=}"; shift ;;
      --allow-downgrade) allow_downgrade_mode="true"; shift ;;
      --allow-unsupported-eol-os) allow_unsupported_eol_os_mode="true"; shift ;;
      --skip-health-check) skip_health_check_mode="true"; shift ;;
      --dry-run) dry_run_mode="true"; shift ;;
      -h|--help) exit 0 ;;
      *) die "Unknown argument: $1" ;;
    esac
  done

  if [[ -z "$release_channel" ]]; then
    if [[ "$license_url" == *"staging"* ]]; then
      release_channel="staging"
    else
      release_channel="stable"
    fi
  fi

  local dash_url order_url
  if [[ "$license_url" == *"staging"* ]]; then
    dash_url="${WPCLOUDOPS_DASH_URL:-https://staging-dash.wpcloudops.com}"
    order_url="${WPCLOUDOPS_ORDER_URL:-https://staging-order.wpcloudops.com}"
  else
    dash_url="${WPCLOUDOPS_DASH_URL:-https://dash.wpcloudops.com}"
    order_url="${WPCLOUDOPS_ORDER_URL:-https://order.wpcloudops.com}"
  fi

  if [[ -z "$LICENSE_KEY" ]]; then
    if [[ ! -t 0 ]]; then
      IFS= read -r LICENSE_KEY || true
      LICENSE_KEY="$(echo "${LICENSE_KEY:-}" | tr -d ' \n\r\t')"
    fi

    if [[ -z "$LICENSE_KEY" && -c /dev/tty && ( -t 1 || -t 2 ) ]]; then
      print_adaptive_header
      read -rsp "Enter WP CloudOps License Key: " LICENSE_KEY < /dev/tty || true
      printf '\n' >&2
      LICENSE_KEY="$(echo "${LICENSE_KEY:-}" | tr -d ' \n\r\t')"
    fi
  fi

  [[ -n "$LICENSE_KEY" ]] || die "A valid license key is required. Set WPCLOUDOPS_LICENSE_KEY, pipe via stdin, or enter at the secure prompt."

  local key_regex='^(wpco_(live|comm)_[A-Za-z0-9_-]{3,118}|WPCO-(PRO|COMM|ENT)-V[0-9]+-[A-Fa-f0-9]{16,64})$'
  if ! [[ "$LICENSE_KEY" =~ $key_regex ]]; then
    printf '\n[CRITICAL] Invalid license key format. Expected WPCO-PRO-V2-... or wpco_comm_... prefix.\n' >&2
    printf 'Please verify your license key at %s\n\n' "$license_url" >&2
    exit 1
  fi

  if [[ -z "${WPCLOUDOPS_HEADER_PRINTED:-}" ]]; then
    print_adaptive_header
    WPCLOUDOPS_HEADER_PRINTED="true"
  fi

  info "Deriving host hardware fingerprint for cryptographic lease binding..."
  local HARDWARE_FP
  HARDWARE_FP=$("$python_bin" - <<'PY'
import hashlib, os, re, subprocess, sys

def get_hardware_fingerprint() -> str:
    components = []
    machine_id = ""
    for path in ["/etc/machine-id", "/var/lib/dbus/machine-id"]:
        if os.path.isfile(path):
            try:
                with open(path, "r", encoding="utf-8") as f:
                    val = f.read().strip()
                    if val and val != "00000000000000000000000000000000":
                        machine_id = val
                        break
            except Exception:
                pass
    if not machine_id and sys.platform == "darwin":
        try:
            out = subprocess.check_output(["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"], stderr=subprocess.DEVNULL).decode()
            m = re.search(r'"IOPlatformUUID"\s*=\s*"([^"]+)"', out)
            if m:
                machine_id = m.group(1).strip()
        except Exception:
            pass
    if not machine_id:
        raise RuntimeError("MACHINE_ID_UNAVAILABLE")
    components.append(machine_id)

    sys_uuid = ""
    for path in ["/sys/class/dmi/id/product_uuid", "/etc/hostid"]:
        if os.path.isfile(path):
            try:
                with open(path, "r", encoding="utf-8") as f:
                    val = f.read().strip()
                    if val and val != "00000000-0000-0000-0000-000000000000":
                        sys_uuid = val
                        break
            except Exception:
                pass
    if not sys_uuid:
        sys_uuid = machine_id
    components.append(sys_uuid)

    cpu_model = ""
    if os.path.isfile("/proc/cpuinfo"):
        try:
            with open("/proc/cpuinfo", "r", encoding="utf-8") as f:
                for line in f:
                    if re.match(r"^(model name|Hardware|Processor)\s*:", line, re.I):
                        cpu_model = line.split(":", 1)[1].strip()
                        break
        except Exception:
            pass
    if not cpu_model and sys.platform == "darwin":
        try:
            cpu_model = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"], stderr=subprocess.DEVNULL).decode().strip()
        except Exception:
            pass
    if not cpu_model:
        cpu_model = "GENERIC_HOST_CPU"
    components.append(cpu_model)

    raw_seed = ":".join(components).encode("utf-8")
    return hashlib.sha256(raw_seed).hexdigest()

try:
    print(get_hardware_fingerprint())
except Exception as e:
    sys.stderr.write(f"ERROR: {e}\n")
    sys.exit(1)
PY
) || die "Failed to derive deterministic hardware fingerprint."

  local os_distro="ubuntu" os_version="24.04" os_arch
  os_arch="$(uname -m)"
  if [[ -f /etc/os-release ]]; then
    # shellcheck disable=SC1091
    source /etc/os-release
    os_distro="${ID:-ubuntu}"
    os_version="${VERSION_ID:-24.04}"
  fi

  info "Hardware Fingerprint: ${HARDWARE_FP:0:16}... (derived)"
  info "Target Platform: ${os_distro} ${os_version} (${os_arch})"

  info "Authorizing release transfer with control plane (${license_url})..."
  local auth_payload
  auth_payload=$(printf '%s\n' "$LICENSE_KEY" | "$python_bin" -c '
import json, sys
key = sys.stdin.readline().strip()
data = {
    "license_key": key,
    "hardware_fingerprint": sys.argv[1],
    "architecture": sys.argv[2],
    "os_release": {
        "distro": sys.argv[3],
        "version": sys.argv[4],
        "arch": sys.argv[2]
    }
}
if len(sys.argv) > 5 and sys.argv[5]:
    data["version"] = sys.argv[5]
if len(sys.argv) > 6 and sys.argv[6]:
    data["channel"] = sys.argv[6]
print(json.dumps(data))
' "$HARDWARE_FP" "$os_arch" "$os_distro" "$os_version" "$target_version" "$release_channel")

  local http_code=""
  AUTH_RESP_TMP="$(mktemp "/tmp/wpco_auth.XXXXXX")"
  http_code=$(printf '%s' "$auth_payload" | "$curl_bin" -sS -w '%{http_code}' -o "$AUTH_RESP_TMP" \
    -X POST "${license_url}/v1/releases/authorize" \
    -H "Content-Type: application/json" \
    --data-binary @- || true)

  local auth_resp
  auth_resp="$(cat "$AUTH_RESP_TMP" 2>/dev/null || true)"
  rm -f "$AUTH_RESP_TMP" 2>/dev/null || true

  if [[ "$http_code" != "200" ]]; then
    local err_msg
    err_msg=$("$python_bin" -c 'import json, sys; d=json.loads(sys.argv[1]) if sys.argv[1] else {}; print(d.get("message") or d.get("error") or "UNKNOWN_ERROR")' "$auth_resp" 2>/dev/null || echo "HTTP_${http_code}")
    printf '\n[CRITICAL] Release authorization failed [HTTP %s]: %s\n' "$http_code" "$err_msg" >&2
    exit 1
  fi

  local grant_token release_ver url_trust_meta url_trust_sig url_manifest url_manifest_sig url_payload
  read -r grant_token release_ver url_trust_meta url_trust_sig url_manifest url_manifest_sig url_payload < <(
    "$python_bin" -c '
import json, sys
try:
    d = json.loads(sys.argv[1])
    assets = d.get("assets", {})
    print(" ".join([
        d.get("grant_token", ""),
        d.get("version", ""),
        assets.get("trust_metadata", ""),
        assets.get("trust_metadata_sig", ""),
        assets.get("manifest", ""),
        assets.get("manifest_sig", ""),
        assets.get("payload", "")
    ]))
except Exception:
    sys.exit(1)
' "$auth_resp"
  ) || die "Failed to parse release authorization response."

  info "Authorization granted for WP CloudOps v${release_ver}."

  STAGING_DIR="$(mktemp -d "/tmp/wpcloudops-bootstrap.XXXXXX")"

  # Helper inside bootstrap to download individual assets
  _dl_asset() {
    local a_path="$1" d_path="$2" f_url
    if [[ "$a_path" =~ ^https?:// ]]; then
      f_url="$a_path"
    else
      f_url="${license_url}${a_path}"
    fi
    "$curl_bin" -fsSL \
      -H "Authorization: Bearer ${grant_token}" \
      -H "X-Hardware-Proof: ${HARDWARE_FP}" \
      -o "$d_path" "$f_url" || die "Failed to download asset: ${a_path}"
  }

  _dl_all() {
    _dl_asset "$url_trust_meta" "${STAGING_DIR}/trust-metadata.json"
    _dl_asset "$url_trust_sig" "${STAGING_DIR}/trust-metadata.json.rtasig"
    _dl_asset "$url_manifest" "${STAGING_DIR}/manifest.json"
    _dl_asset "$url_manifest_sig" "${STAGING_DIR}/manifest.json.minisig"
    _dl_asset "$url_payload" "${STAGING_DIR}/wpcloudops-${release_ver}.tar.gz"
  }

  run_with_cloud_pulse "Transferring release supply-chain artifacts over TLS" _dl_all

  mkdir -p "${STAGING_DIR}/trust"
  local rta_pub_path="${STAGING_DIR}/trust/rta.pub"
  if [[ -n "${WPCLOUDOPS_RTA_PUB:-}" && -f "$WPCLOUDOPS_RTA_PUB" ]]; then
    cp "$WPCLOUDOPS_RTA_PUB" "$rta_pub_path"
  elif [[ -f "/etc/wpcloudops/trust/rta.pub" ]]; then
    cp "/etc/wpcloudops/trust/rta.pub" "$rta_pub_path"
  else
    cat <<'PUB' > "$rta_pub_path"
xl9U72z8K/e/B8EwV1qzgYtP1cTt9X45fc2FMv9Q6bQ=
PUB
  fi
  chmod 0644 "$rta_pub_path"

  local external_inst=""
  if [[ -x "${install_root_dir}/current/tools/wpcloudops-install.sh" ]]; then
    external_inst="${install_root_dir}/current/tools/wpcloudops-install.sh"
  fi

  local install_cmd=()
  if [[ -n "$external_inst" ]]; then
    install_cmd=(
      "$external_inst"
      "--manifest" "${STAGING_DIR}/manifest.json"
      "--signature" "${STAGING_DIR}/manifest.json.minisig"
      "--payload" "${STAGING_DIR}/wpcloudops-${release_ver}.tar.gz"
      "--trust-metadata" "${STAGING_DIR}/trust-metadata.json"
      "--rta-pub" "$rta_pub_path"
      "--install-root" "$install_root_dir"
    )
  else
    info "Validating payload digest against signed manifest before extraction..."
    "$python_bin" - "${STAGING_DIR}/manifest.json" "${STAGING_DIR}/wpcloudops-${release_ver}.tar.gz" <<'PY' || die "Payload digest does not match manifest."
import json, hashlib, sys
manifest_path, payload_path = sys.argv[1], sys.argv[2]
try:
    with open(manifest_path, 'r', encoding='utf-8') as f:
        m = json.load(f)
    expected_sha = m.get('artifacts', {}).get('payload', {}).get('sha256', '')
    if not expected_sha or len(expected_sha) != 64:
        sys.exit(1)
    hasher = hashlib.sha256()
    with open(payload_path, 'rb') as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b''):
            hasher.update(chunk)
    if hasher.hexdigest().lower() != expected_sha.lower():
        sys.exit(2)
except Exception:
    sys.exit(3)
PY

    mkdir -p "${STAGING_DIR}/engine"
    "$tar_bin" -xzf "${STAGING_DIR}/wpcloudops-${release_ver}.tar.gz" \
      -C "${STAGING_DIR}/engine" \
      tools/wpcloudops-install.sh lib/ || die "Failed to extract installer from release payload."

    install_cmd=(
      "${STAGING_DIR}/engine/tools/wpcloudops-install.sh"
      "--manifest" "${STAGING_DIR}/manifest.json"
      "--signature" "${STAGING_DIR}/manifest.json.minisig"
      "--payload" "${STAGING_DIR}/wpcloudops-${release_ver}.tar.gz"
      "--trust-metadata" "${STAGING_DIR}/trust-metadata.json"
      "--rta-pub" "$rta_pub_path"
      "--install-root" "$install_root_dir"
    )
  fi

  if [[ "$allow_downgrade_mode" == "true" ]]; then
    install_cmd+=("--allow-downgrade")
  fi
  if [[ "$allow_unsupported_eol_os_mode" == "true" ]]; then
    install_cmd+=("--allow-unsupported-eol-os")
  fi
  if [[ "$skip_health_check_mode" == "true" ]]; then
    install_cmd+=("--skip-health-check")
  fi

  if [[ "$dry_run_mode" == "true" ]]; then
    install_cmd+=("--dry-run")
    info "Executing pre-flight supply chain verification in dry-run mode..."
    "${install_cmd[@]}"
    info "[SUCCESS] Dry-run verification completed cleanly."
    return 0
  fi

  run_with_cloud_pulse "Executing atomic release installation to ${install_root_dir}" "${install_cmd[@]}"

  local trust_dest_dir="${WPCLOUDOPS_TRUST_DIR:-/etc/wpcloudops/trust}"
  if mkdir -p "$trust_dest_dir" 2>/dev/null; then
    cp -f "$rta_pub_path" "${trust_dest_dir}/rta.pub"
    chmod 0644 "${trust_dest_dir}/rta.pub" 2>/dev/null || true
    if [[ -f "${STAGING_DIR}/trust-metadata.json" ]]; then
      cp -f "${STAGING_DIR}/trust-metadata.json" "${trust_dest_dir}/trust-metadata.json"
      chmod 0644 "${trust_dest_dir}/trust-metadata.json" 2>/dev/null || true
    fi
    if [[ -f "${STAGING_DIR}/trust-metadata.json.rtasig" ]]; then
      cp -f "${STAGING_DIR}/trust-metadata.json.rtasig" "${trust_dest_dir}/trust-metadata.json.rtasig"
      chmod 0644 "${trust_dest_dir}/trust-metadata.json.rtasig" 2>/dev/null || true
    fi
  fi

  local config_dest_dir="${WPCLOUDOPS_CONFIG_DIR:-/etc/wpcloudops}"
  if mkdir -p "$config_dest_dir" 2>/dev/null; then
    cat <<EOF > "${config_dest_dir}/licensing.env"
WPCLOUDOPS_LICENSE_ENDPOINT="${license_url}"
WPCLOUDOPS_LICENSE_URL="${license_url}"
EOF
    chmod 0644 "${config_dest_dir}/licensing.env" 2>/dev/null || true
  fi

  local manage_lic_bin="${install_root_dir}/current/tools/manage-license.sh"
  if [[ -x "$manage_lic_bin" ]]; then
    info "Binding node to license seat via control plane (${license_url})..."
    printf '%s\n' "$LICENSE_KEY" | WPCLOUDOPS_LICENSE_URL="$license_url" WPCLOUDOPS_LICENSE_ENDPOINT="$license_url" "$manage_lic_bin" bind "$license_url" || {
      warn "Automated node bind returned non-zero. Bind manually via: sudo wpco license activate <LICENSE_KEY>"
    }
  fi

  local agent_bin="${install_root_dir}/current/tools/wpcloudops-agent.sh"
  if [[ -x "$agent_bin" ]]; then
    info "Registering node as managed server in control plane..."
    WPCLOUDOPS_LICENSE_URL="$license_url" WPCLOUDOPS_LICENSE_ENDPOINT="$license_url" "$agent_bin" enroll --nickname="$(hostname -s 2>/dev/null || echo "server")" || {
      warn "Agent enrollment notice. Outbound agent service will retry on start."
    }
  fi

  check_binary_shadowing "wpcloudops" "/usr/local/bin/wpcloudops"
  check_binary_shadowing "wpco" "/usr/local/bin/wpco"
  info "WPCloudOps Engine v${target_version} successfully installed!"
  print_completion_card "$release_ver" "$install_root_dir" "$license_url"
}

# -----------------------------------------------------------------------------
# Entrypoint Dispatch
# -----------------------------------------------------------------------------
if [[ "$IS_LOCAL_VERIFY_MODE" == "false" ]]; then
  run_remote_bootstrap "$@"
  exit 0
fi

# -----------------------------------------------------------------------------
# LOCAL PACKAGE VERIFICATION & ENGINE ACTIVATION WORKFLOW (MODE B)
# -----------------------------------------------------------------------------
# shellcheck disable=SC1091
if [[ -f "${SCRIPT_DIR}/lib/artifact-verifier.sh" ]]; then
  source "${SCRIPT_DIR}/lib/artifact-verifier.sh"
elif [[ -f "${ROOT_DIR}/lib/artifact-verifier.sh" ]]; then
  source "${ROOT_DIR}/lib/artifact-verifier.sh"
elif [[ -f "/opt/wpcloudops/current/lib/artifact-verifier.sh" ]]; then
  source "/opt/wpcloudops/current/lib/artifact-verifier.sh"
else
  printf '[CRITICAL] Required verifier module lib/artifact-verifier.sh not found.\n' >&2
  exit 1
fi

usage() {
  cat <<'EOF' >&2
Usage: wpcloudops-install.sh [OPTIONS]

Required Options:
  --manifest PATH          Path to manifest.json (or directory containing release bundle)
  --signature PATH         Path to manifest.json.minisig
  --payload PATH           Path to payload archive (wpcloudops-*.tar.gz)

Optional Options:
  --trust-metadata PATH    Path to trust-metadata.json (default: /etc/wpcloudops/trust/trust-metadata.json)
  --rta-pub PATH           Path to rta.pub (default: /etc/wpcloudops/trust/rta.pub)
  --install-root PATH      Installation root directory (default: /opt/wpcloudops)
  --allow-unsupported-eol-os
                           Bypass Ubuntu 20.04 ESM requirement (isolated test environments only)
  --allow-downgrade        Allow installation of lower release_seq (requires interactive confirmation)
  --skip-health-check      Skip post-swap health check validation
  --dry-run                Perform cryptographic and archive verification without modifying active release
  -h, --help               Show this help message
EOF
}

die() {
  printf '[CRITICAL] %s\n' "$*" >&2
  scan_and_diagnose_failure "$*" 1
  exit 1
}

# -----------------------------------------------------------------------------
# Diagnostic & Failure Analysis Assistant
# -----------------------------------------------------------------------------
scan_and_diagnose_failure() {
  local error_output="$1"
  local rc="${2:-1}"

  if [[ -t 1 || -t 2 ]]; then
    printf "\n\033[0;31m┌─ WP CloudOps Diagnostic Assistant ───────────────────────┐\033[0m\n" >&2
    printf "\033[0;31m│ Step exit status: %-38s │\033[0m\n" "$rc" >&2
    if [[ "$error_output" =~ "Text file busy" || "$error_output" =~ "ETXTBSY" || "$error_output" =~ "EEXIST" ]]; then
      printf "\033[0;31m│ Cause: File system lock or running process active.        │\033[0m\n" >&2
      printf "│ Action: Active processes may be holding execution locks. │\n" >&2
      if command -v fuser >/dev/null 2>&1; then
        local locked_pids
        locked_pids=$(fuser "/opt/wpcloudops/current" 2>/dev/null || true)
        if [[ -n "$locked_pids" ]]; then
          printf "│ Active PIDs: %-43s │\n" "$locked_pids" >&2
        fi
      fi
    elif [[ "$error_output" =~ "ETIMEDOUT" || "$error_output" =~ "Connection refused" || "$error_output" =~ "Could not resolve" ]]; then
      printf "\033[0;31m│ Cause: Network reachability / firewall egress issue.     │\033[0m\n" >&2
      printf "│ Action: Verify outbound HTTPS (port 443) connectivity     │\n" >&2
      printf "│         to control plane licensing endpoint.             │\n" >&2
    elif [[ "$error_output" =~ "ENOSPC" || "$error_output" =~ "No space left on device" ]]; then
      printf "\033[0;31m│ Cause: Storage disk exhaustion or inode saturation.       │\033[0m\n" >&2
      printf "│ Action: Check free space and inodes via: df -h /opt      │\n" >&2
    elif [[ "$error_output" =~ "minisign" || "$error_output" =~ "signature" || "$error_output" =~ "Trusted Comment" ]]; then
      printf "\033[0;31m│ Cause: Cryptographic trust verification failed.          │\033[0m\n" >&2
      printf "│ Action: Verify system clock synchronization (NTP). Stale  │\n" >&2
      printf "│         clock skew or untrusted RTA keys reject releases. │\n" >&2
    fi
    printf "\033[0;31m└──────────────────────────────────────────────────────────┘\033[0m\n\n" >&2
  fi
}

check_binary_shadowing() {
  local cmd_name="$1"
  local target_path="$2"

  local active_bin
  active_bin=$(command -v "$cmd_name" 2>/dev/null || true)

  if [[ -z "$active_bin" ]]; then
    if [[ ":$PATH:" != *":/usr/local/bin:"* ]]; then
      if [[ -t 1 || -t 2 ]]; then
        printf "\n\033[0;33m┌─ WP CloudOps PATH Diagnostic ─────────────────────────────┐\n" >&2
        printf "│ ⚠ NOTICE: '%s' is installed at %s,\n" "$cmd_name" "$target_path" >&2
        printf "│   but /usr/local/bin is missing from your PATH.          │\n" >&2
        printf "│                                                          │\n" >&2
        printf "│ Recommended action:                                      │\n" >&2
        printf "│   export PATH=\"/usr/local/bin:\$PATH\"                    │\n" >&2
        printf "└──────────────────────────────────────────────────────────┘\033[0m\n\n" >&2
      else
        printf '[WARN] %s installed at %s but /usr/local/bin is not in PATH. Run: export PATH="/usr/local/bin:$%s"\n' "$cmd_name" "$target_path" "PATH" >&2
      fi
    fi
    return 0
  fi

  local resolved_active resolved_target
  resolved_active=$(readlink -f "$active_bin" 2>/dev/null || true)
  resolved_target=$(readlink -f "$target_path" 2>/dev/null || true)

  if [[ "$active_bin" != "$target_path" && ( -z "$resolved_active" || "$resolved_active" != "$resolved_target" ) ]]; then
    if [[ -t 1 || -t 2 ]]; then
      printf "\n\033[0;33m┌─ WP CloudOps PATH Diagnostic ─────────────────────────────┐\n" >&2
      printf "│ ⚠ NOTICE: Another binary '%s' exists at:         │\n" "$cmd_name" >&2
      printf "│   %-54s │\n" "$active_bin" >&2
      printf "│ Target installation is linked at:                        │\n" >&2
      printf "│   %-54s │\n" "$target_path" >&2
      printf "│                                                          │\n" >&2
      printf "│ Recommended action:                                      │\n" >&2
      printf "│   sudo rm -f %-43s │\n" "$active_bin" >&2
      printf "└──────────────────────────────────────────────────────────┘\033[0m\n\n" >&2
    else
      printf '[WARN] Another binary for %s exists at %s, which shadows %s. Consider removing %s.\n' "$cmd_name" "$active_bin" "$target_path" "$active_bin" >&2
    fi
  fi
}

setup_global_symlinks() {
  local target_bin="${install_root}/current/tools/wpcloudops-agent.sh"
  if [[ ! -x "$target_bin" && -x "${install_root}/current/tools/wpcloudops-install.sh" ]]; then
    target_bin="${install_root}/current/tools/wpcloudops-install.sh"
  fi

  if [[ -d "/usr/local/bin" && -w "/usr/local/bin" ]]; then
    local tmp_stage
    tmp_stage=$(mktemp -d "/usr/local/bin/.wpco.stage.XXXXXX" 2>/dev/null || true)
    if [[ -n "$tmp_stage" && -d "$tmp_stage" ]]; then
      ln -sfn "$target_bin" "${tmp_stage}/wpcloudops"
      ln -sfn "$target_bin" "${tmp_stage}/wpco"
      mv -f "${tmp_stage}/wpcloudops" "/usr/local/bin/wpcloudops"
      mv -f "${tmp_stage}/wpco" "/usr/local/bin/wpco"
      rm -rf "$tmp_stage" 2>/dev/null || true
    else
      ln -sfn "$target_bin" "/usr/local/bin/wpcloudops" 2>/dev/null || true
      ln -sfn "$target_bin" "/usr/local/bin/wpco" 2>/dev/null || true
    fi
  fi
}

# -----------------------------------------------------------------------------
# CLI Argument Parsing
# -----------------------------------------------------------------------------
manifest=""
signature=""
payload=""
trust_metadata=""
rta_pub=""
install_root="/opt/wpcloudops"
allow_unsupported_eol_os="false"
allow_downgrade="false"
skip_health_check="false"
dry_run="false"

while (($#)); do
  case "$1" in
    --manifest|--signature|--payload|--trust-metadata|--rta-pub|--install-root)
      (($# >= 2)) || { usage; die "$1 requires an argument"; }
      key="$1"; value="$2"; shift 2
      case "$key" in
        --manifest) manifest="$value" ;;
        --signature) signature="$value" ;;
        --payload) payload="$value" ;;
        --trust-metadata) trust_metadata="$value" ;;
        --rta-pub) rta_pub="$value" ;;
        --install-root) install_root="$value" ;;
      esac
      ;;
    --manifest=*)
      manifest="${1#*=}"
      shift
      ;;
    --signature=*)
      signature="${1#*=}"
      shift
      ;;
    --payload=*)
      payload="${1#*=}"
      shift
      ;;
    --trust-metadata=*)
      trust_metadata="${1#*=}"
      shift
      ;;
    --rta-pub=*)
      rta_pub="${1#*=}"
      shift
      ;;
    --install-root=*)
      install_root="${1#*=}"
      shift
      ;;
    --allow-unsupported-eol-os)
      allow_unsupported_eol_os="true"
      shift
      ;;
    --allow-downgrade)
      allow_downgrade="true"
      shift
      ;;
    --skip-health-check)
      skip_health_check="true"
      shift
      ;;
    --dry-run)
      dry_run="true"
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      usage
      die "Unknown option: $1"
      ;;
  esac
done

# If manifest is a directory, locate bundle files automatically
if [[ -n "$manifest" && -d "$manifest" && -z "$signature" && -z "$payload" ]]; then
  bundle_dir="$manifest"
  manifest="${bundle_dir}/manifest.json"
  signature="${bundle_dir}/manifest.json.minisig"
fi

[[ -n "$manifest" ]] || { usage; die "Missing required --manifest argument"; }
[[ -n "$signature" ]] || { usage; die "Missing required --signature argument"; }
if [[ -z "${bundle_dir:-}" ]]; then
  [[ -n "$payload" ]] || { usage; die "Missing required --payload argument"; }
fi

[[ -f "$manifest" && ! -L "$manifest" ]] || die "Manifest file is missing or a symlink: $manifest"
[[ -f "$signature" && ! -L "$signature" ]] || die "Signature file is missing or a symlink: $signature"
if [[ -n "$payload" ]]; then
  [[ -f "$payload" && ! -L "$payload" ]] || die "Payload file is missing or a symlink: $payload"
fi

if [[ -z "$trust_metadata" ]]; then
  trust_metadata="/etc/wpcloudops/trust/trust-metadata.json"
fi

if [[ -z "$rta_pub" ]]; then
  rta_pub="/etc/wpcloudops/trust/rta.pub"
fi

[[ -f "$trust_metadata" && ! -L "$trust_metadata" ]] || die "Trust metadata file is missing or a symlink: $trust_metadata"
[[ -f "$rta_pub" && ! -L "$rta_pub" ]] || die "RTA public key anchor is missing or a symlink: $rta_pub"

# -----------------------------------------------------------------------------
# Setup Layout Paths
# -----------------------------------------------------------------------------
releases_dir="${install_root}/releases"
current_link="${install_root}/current"
version_state="${install_root}/version.state"
journal_file="${install_root}/install-journal.json"

mkdir -p "$install_root" "$releases_dir"

# -----------------------------------------------------------------------------
# 0. Acquire Non-Blocking Exclusive Mutex
# -----------------------------------------------------------------------------
lock_file="${WPCLOUDOPS_INSTALL_LOCK_FILE:-/run/lock/wpcloudops-install.lock}"
if ! mkdir -p "$(dirname "$lock_file")" 2>/dev/null || [[ ! -w "$(dirname "$lock_file")" ]]; then
  lock_file="${TMPDIR:-/tmp}/wpcloudops-install.lock"
fi
exec 200>"$lock_file"
if command -v flock >/dev/null 2>&1; then
  if ! flock -n 200; then
    die "Another installer process is currently running (lock held: $lock_file)."
  fi
else
  if ! "$VERIFIER_PYTHON_BIN" -c "import fcntl; fcntl.flock(200, fcntl.LOCK_EX | fcntl.LOCK_NB)" 2>/dev/null; then
    die "Another installer process is currently running (lock held: $lock_file)."
  fi
fi

# -----------------------------------------------------------------------------
# 1. Crash Recovery Protocol (Pre-Flight)
# -----------------------------------------------------------------------------
if [[ -f "$journal_file" ]]; then
  if [[ "$dry_run" == "true" ]]; then
    printf '[INFO] Prior transaction journal detected. Dry-run mode: reporting torn transaction without modification.\n' >&2
  else
    printf '[INFO] Prior transaction journal detected. Executing crash recovery...\n' >&2
    rec_rc=0
    wpcloudops_recover_torn_transaction "$journal_file" "$releases_dir" "$current_link" "$version_state" || rec_rc=$?
    if [[ "$rec_rc" -ne 0 ]]; then
      die "Automatic crash recovery failed with exit code ${rec_rc}. Operator intervention required."
    fi
  fi
fi

# -----------------------------------------------------------------------------
# 2. Ubuntu 20.04 ESM Entitlement Verification
# -----------------------------------------------------------------------------
printf '[INFO] Checking host OS and Ubuntu 20.04 ESM entitlement...\n' >&2
wpcloudops_check_ubuntu_esm_eligibility "$allow_unsupported_eol_os" || die "Platform eligibility check failed."

# -----------------------------------------------------------------------------
# 3. Stage Protected Bundle & Cryptographic Verification
# -----------------------------------------------------------------------------
bundle_stage_dir="$(mktemp -d "${install_root}/.bundle.stage.XXXXXX" 2>/dev/null || mktemp -d "/tmp/.wpcloudops.bundle.stage.XXXXXX")"
chmod 0700 "$bundle_stage_dir"
trap 'rm -rf "$bundle_stage_dir" 2>/dev/null || true' EXIT

staged_manifest="${bundle_stage_dir}/manifest.json"
staged_signature="${bundle_stage_dir}/manifest.json.minisig"
staged_payload="${bundle_stage_dir}/payload.tar.gz"

cp -p "$manifest" "$staged_manifest"
cp -p "$signature" "$staged_signature"
chmod 0600 "$staged_manifest" "$staged_signature"

manifest="$staged_manifest"
signature="$staged_signature"

installed_meta_seq="-1"
if [[ -f "$version_state" ]]; then
  s_seq=$(grep '^TRUST_METADATA_SEQ=' "$version_state" 2>/dev/null | cut -d'=' -f2- | tr -d ' "\r\n' || true)
  [[ -n "$s_seq" && "$s_seq" =~ ^[0-9]+$ ]] && installed_meta_seq="$s_seq"
fi

printf '[INFO] Verifying Minisign signature against authenticated trust anchor...\n' >&2
verify_out=""
verify_out=$(wpcloudops_verify_minisign "$manifest" "$signature" "$trust_metadata" "$rta_pub" "" "$installed_meta_seq") || die "Manifest Minisign verification failed."

verified_trust_meta_seq=""
verified_trust_meta_seq=$("$VERIFIER_PYTHON_BIN" - "$verify_out" <<'PY'
import json, sys
try:
    data = json.loads(sys.argv[1])
    seq = data.get('trust_metadata_seq')
    if seq is not None and str(seq).isdigit():
        print(seq)
        sys.exit(0)
except Exception:
    pass
sys.exit(1)
PY
) || die "Minisign verification output missing valid trust_metadata_seq."

# Resolve payload from verified manifest if bundle_dir was used, or verify explicitly supplied payload
if [[ -n "${bundle_dir:-}" && -z "${payload:-}" ]]; then
  manifest_payload_name=$("$VERIFIER_PYTHON_BIN" -c "import json, sys; print(json.load(open(sys.argv[1])).get('artifacts',{}).get('payload',{}).get('path',''))" "$manifest" 2>/dev/null || true)
  [[ -n "$manifest_payload_name" ]] || die "Manifest artifacts.payload.path is missing or empty"
  payload="${bundle_dir}/${manifest_payload_name}"
fi

[[ -f "$payload" && ! -L "$payload" ]] || die "Payload file is missing or a symlink: $payload"
cp -p "$payload" "$staged_payload"
chmod 0600 "$staged_payload"
payload="$staged_payload"

# -----------------------------------------------------------------------------
# 4. Extract Manifest Metadata & Validate Expected Payload Digest
# -----------------------------------------------------------------------------
manifest_meta=""
manifest_meta="$("$VERIFIER_PYTHON_BIN" - "$manifest" "$payload" <<'PY'
import json, hashlib, sys, os

manifest_path, payload_path = sys.argv[1], sys.argv[2]
with open(manifest_path, 'r', encoding='utf-8') as f:
    m = json.load(f)

build_id = str(m.get('build_id', '')).strip()
version = str(m.get('version', '')).strip()
release_seq = m.get('release_seq')
if not isinstance(release_seq, int) or release_seq <= 0:
    sys.exit("Invalid or non-positive release_seq in manifest")

artifacts = m.get('artifacts', {})
payload_spec = artifacts.get('payload', {})
expected_sha = payload_spec.get('sha256', '')
if not expected_sha or len(expected_sha) != 64:
    sys.exit("Invalid or missing artifacts.payload.sha256 in manifest")

with open(manifest_path, 'rb') as f:
    manifest_sha = hashlib.sha256(f.read()).hexdigest()

print(f"{build_id}\t{version}\t{release_seq}\t{expected_sha}\t{manifest_sha}")
PY
)" || die "Failed to parse and validate manifest metadata."

IFS=$'\t' read -r build_id version release_seq expected_payload_sha manifest_sha <<< "$manifest_meta"

[[ -n "$build_id" && "$build_id" =~ ^[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*$ && ${#build_id} -le 64 ]] || \
  die "Manifest build_id does not conform to strict identifier grammar: ${build_id:-}"

# -----------------------------------------------------------------------------
# 5. Anti-Downgrade & Monotonic Release Sequence Enforcement
# -----------------------------------------------------------------------------
printf '[INFO] Checking anti-downgrade and monotonic release sequence...\n' >&2
wpcloudops_check_anti_downgrade "$manifest" "$version_state" "$allow_downgrade" || die "Anti-downgrade gate rejected installation."

if [[ "$dry_run" == "true" ]]; then
  printf '[INFO] Dry run requested. Validating streaming archive without persistent installation...\n' >&2
  wpcloudops_verify_archive "$payload" "$expected_payload_sha" "" || die "Streaming archive validation failed on dry run."
  printf '[SUCCESS] Dry run completed cleanly. Manifest, signature, platform, and archive limits verified.\n'
  exit 0
fi

# -----------------------------------------------------------------------------
# 6. Capture Previous Release State
# -----------------------------------------------------------------------------
prev_build_id=""
if [[ -L "$current_link" ]]; then
  current_target="$(readlink "$current_link" || true)"
  prev_build_id="$(basename "$current_target")"
  if [[ "$prev_build_id" == "$build_id" ]]; then
    printf '[WARN] Reinstalling currently active build ID: %s\n' "$build_id" >&2
  fi
fi

# -----------------------------------------------------------------------------
# 7. Helper: Atomic Durable Journal Writer with Directory Fsync
# -----------------------------------------------------------------------------
write_durable_journal() {
  local stage="$1"
  local t_trust="${verified_trust_meta_seq:-$installed_meta_seq}"
  "$VERIFIER_PYTHON_BIN" - "$journal_file" "$stage" "$build_id" "$prev_build_id" "$release_seq" "$manifest_sha" "${t_trust:-}" <<'PY'
import json, os, sys, time

j_path, stage, target_bid, prev_bid, seq, m_sha, t_trust = sys.argv[1:]
journal_data = {
    "transaction_id": f"tx-{os.getpid()}-{seq}",
    "stage": stage,
    "target_build_id": target_bid,
    "previous_build_id": prev_bid,
    "target_release_seq": int(seq),
    "target_manifest_sha256": m_sha,
    "target_trust_metadata_seq": int(t_trust) if (t_trust and t_trust.isdigit()) else None,
    "updated_at": int(time.time())
}

tmp_path = f"{j_path}.tmp.{os.getpid()}"
with open(tmp_path, 'w', encoding='utf-8') as f:
    json.dump(journal_data, f, indent=2)
    f.flush()
    os.fsync(f.fileno())

os.replace(tmp_path, j_path)
parent_fd = os.open(os.path.dirname(os.path.abspath(j_path)), os.O_RDONLY)
try:
    os.fsync(parent_fd)
finally:
    os.close(parent_fd)
PY
}

# -----------------------------------------------------------------------------
# 8. Stage 1: STAGED Journal & Streaming Three-Pass Extraction
# -----------------------------------------------------------------------------
actual_payload_sha="$(shasum -a 256 "$payload" 2>/dev/null | awk '{print $1}' || sha256sum "$payload" 2>/dev/null | awk '{print $1}' || true)"
[[ "$actual_payload_sha" == "$expected_payload_sha" ]] || \
  die "Payload SHA-256 digest ($actual_payload_sha) does not match expected ($expected_payload_sha). Aborting before staging."

printf '[INFO] Recording transaction stage: STAGED\n' >&2
write_durable_journal "STAGED"

staging_dir="${releases_dir}/.staging.${build_id}"
target_dir="${releases_dir}/${build_id}"

rm -rf "$staging_dir" 2>/dev/null || true
mkdir -p "$staging_dir"

printf '[INFO] Performing streaming three-pass archive validation and extraction...\n' >&2
extract_rc=0
wpcloudops_verify_archive "$payload" "$expected_payload_sha" "$staging_dir" || extract_rc=$?
if [[ "$extract_rc" -ne 0 ]]; then
  rm -rf "$staging_dir" 2>/dev/null || true
  rm -f "$journal_file" 2>/dev/null || true
  die "Archive verification or extraction failed. Staging cleaned."
fi

# Embed immutable copies of manifest and signature into staged release
cp "$manifest" "${staging_dir}/manifest.json"
cp "$signature" "${staging_dir}/manifest.json.minisig"
chmod 0644 "${staging_dir}/manifest.json" "${staging_dir}/manifest.json.minisig"

# Fsync all files in staging directory prior to promotion
"$VERIFIER_PYTHON_BIN" - "$staging_dir" <<'PY'
import os, sys
src = sys.argv[1]
for root, dirs, files in os.walk(src):
    for f in files:
        fpath = os.path.join(root, f)
        if not os.path.islink(fpath):
            fd = os.open(fpath, os.O_RDONLY)
            try:
                os.fsync(fd)
            finally:
                os.close(fd)
    dfd = os.open(root, os.O_RDONLY)
    try:
        os.fsync(dfd)
    finally:
        os.close(dfd)
PY

# Promote staged directory to permanent releases directory
retiring_dir=""
if [[ "$prev_build_id" == "$build_id" && -d "$target_dir" ]]; then
  # Identical release reinstall: target_dir is already active and healthy. Keep in place without moving out from under current
  rm -rf "$staging_dir" 2>/dev/null || true
else
  if [[ -d "$target_dir" && "$target_dir" != "$staging_dir" ]]; then
    rm -rf "$target_dir" 2>/dev/null || true
  fi
  mv -f "$staging_dir" "$target_dir"
fi

"$VERIFIER_PYTHON_BIN" - "$target_dir" <<'PY'
import os, sys
dst = sys.argv[1]
p_fd = os.open(os.path.dirname(os.path.abspath(dst)), os.O_RDONLY)
try:
    os.fsync(p_fd)
finally:
    os.close(p_fd)
PY

# Preserve bundle staging cleanup trap and retain retiring_dir until commitment succeeds
trap 'rm -rf "$bundle_stage_dir" 2>/dev/null || true' EXIT

# -----------------------------------------------------------------------------
# 9. Stage 2: PREPARED Journal
# -----------------------------------------------------------------------------
printf '[INFO] Recording transaction stage: PREPARED\n' >&2
write_durable_journal "PREPARED"

# -----------------------------------------------------------------------------
# 10. Stage 3: Atomic Symlink Switch (rename(2) semantics) & POINTER_SWITCHED
# -----------------------------------------------------------------------------
printf '[INFO] Atomically switching active release symlink to %s...\n' "$build_id" >&2
temp_symlink="${current_link}.tmp.$$"
ln -sfn "releases/${build_id}" "$temp_symlink"

swap_rc=0
wpcloudops_swap_active_release "$temp_symlink" "$current_link" || swap_rc=$?
if [[ "$swap_rc" -ne 0 ]]; then
  rm -f "$temp_symlink" 2>/dev/null || true
  die "Atomic symlink replacement failed. Reverting to recovery."
fi

write_durable_journal "POINTER_SWITCHED"

# -----------------------------------------------------------------------------
# 11. Post-Switch Health Checks
# -----------------------------------------------------------------------------
if [[ "$skip_health_check" != "true" ]]; then
  printf '[INFO] Executing post-switch health check validation...\n' >&2
  health_ok="true"

  if [[ -f "${current_link}/setup.sh" ]]; then
    if ! bash -n "${current_link}/setup.sh" >/dev/null 2>&1; then
      health_ok="false"
    elif ! bash "${current_link}/setup.sh" --version >/dev/null 2>&1; then
      health_ok="false"
    fi
  else
    health_ok="false"
  fi

  if [[ "$health_ok" != "true" ]]; then
    printf '[ALERT] Health check failed on newly activated release %s. Initiating automatic rollback...\n' "$build_id" >&2
    write_durable_journal "ROLLING_BACK"

    if [[ -n "$retiring_dir" && -d "$retiring_dir" ]]; then
      rm -rf "$target_dir" 2>/dev/null || true
      mv -f "$retiring_dir" "$target_dir"
      write_durable_journal "ROLLED_BACK"
      rm -f "$journal_file" 2>/dev/null || true
      die "Health checks failed. Restored prior active release directory (${build_id})."
    elif [[ -n "$prev_build_id" && -d "${releases_dir}/${prev_build_id}" ]]; then
      rollback_symlink="${current_link}.rollback.$$"
      ln -sfn "releases/${prev_build_id}" "$rollback_symlink"
      wpcloudops_swap_active_release "$rollback_symlink" "$current_link"
      write_durable_journal "ROLLED_BACK"
      rm -rf "$target_dir" 2>/dev/null || true
      rm -f "$journal_file" 2>/dev/null || true
      die "Health checks failed. Reverted active release to previous known good (${prev_build_id})."
    else
      die "Health checks failed and no previous release is available to revert to."
    fi
  fi
fi

# Clean up retiring directory now that health checks have succeeded
if [[ -n "$retiring_dir" && -d "$retiring_dir" ]]; then
  rm -rf "$retiring_dir" 2>/dev/null || true
fi

# -----------------------------------------------------------------------------
# 12. Commit Monotonic Version State
# -----------------------------------------------------------------------------
printf '[INFO] Committing monotonic version state...\n' >&2
tmp_state="${version_state}.tmp.$$"
{
  printf 'RELEASE_SEQ=%s\n' "$release_seq"
  printf 'VERSION=%s\n' "$version"
  printf 'BUILD_ID=%s\n' "$build_id"
  printf 'MANIFEST_SHA256=%s\n' "$manifest_sha"
  printf 'TRUST_METADATA_SEQ=%s\n' "${verified_trust_meta_seq:-$installed_meta_seq}"
  printf 'COMMITTED_AT=%s\n' "$(date +%s)"
} > "$tmp_state"
chmod 0644 "$tmp_state"

# Fsync temporary state file before atomic rename
"$VERIFIER_PYTHON_BIN" - "$tmp_state" <<'PY'
import os, sys
fd = os.open(sys.argv[1], os.O_RDONLY)
try:
    os.fsync(fd)
finally:
    os.close(fd)
PY

mv -f "$tmp_state" "$version_state"

# Fsync install_root after renaming version_state
"$VERIFIER_PYTHON_BIN" - "$install_root" <<'PY'
import os, sys
p_fd = os.open(sys.argv[1], os.O_RDONLY)
try:
    os.fsync(p_fd)
finally:
    os.close(p_fd)
PY

# -----------------------------------------------------------------------------
# 13. Stage 4: COMMITTED & Journal Removal
# -----------------------------------------------------------------------------
write_durable_journal "COMMITTED"
rm -f "$journal_file" 2>/dev/null || true

# fsync parent directory after journal removal
"$VERIFIER_PYTHON_BIN" - "$install_root" <<'PY'
import os, sys
p_fd = os.open(sys.argv[1], os.O_RDONLY)
try:
    os.fsync(p_fd)
finally:
    os.close(p_fd)
PY

# -----------------------------------------------------------------------------
# 14. Global Symlinks & Runtime Handshake
# -----------------------------------------------------------------------------
setup_global_symlinks

if [[ "$dry_run" != "true" ]]; then
  check_binary_shadowing "wpcloudops" "/usr/local/bin/wpcloudops"
  check_binary_shadowing "wpco" "/usr/local/bin/wpco"

  # Post-swap runtime handshake
  handshake_bin="/usr/local/bin/wpcloudops"
  if [[ ! -x "$handshake_bin" ]]; then
    handshake_bin="${current_link}/tools/wpcloudops-agent.sh"
  fi
  if [[ -x "$handshake_bin" ]]; then
    installed_ver="$("$handshake_bin" --version 2>/dev/null | tr -d '[:space:]' || true)"
    if [[ -n "$installed_ver" ]]; then
      printf '[INFO] Runtime execution handshake verified (%s).\n' "$installed_ver" >&2
    fi
  fi
fi

# -----------------------------------------------------------------------------
# 15. Optional Systemd Unit Registration
# -----------------------------------------------------------------------------
agent_service_src="${current_link}/systemd/wpcloudops-agent.service"
if [[ -f "$agent_service_src" && -d "/etc/systemd/system" ]]; then
  cp -f "$agent_service_src" "/etc/systemd/system/wpcloudops-agent.service" 2>/dev/null || true
  chmod 0644 "/etc/systemd/system/wpcloudops-agent.service" 2>/dev/null || true
  if command -v systemctl >/dev/null 2>&1; then
    systemctl daemon-reload 2>/dev/null || true
  fi
fi

printf '[SUCCESS] WP CloudOps Release %s (build %s, seq %s) installed and activated successfully at %s\n' \
  "$version" "$build_id" "$release_seq" "$install_root"
exit 0
