#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
BUNDLE_ROOT="${1:?bundle root}"; export BUNDLE_ROOT
EXPECTED_PACKAGE_SHA="${2:?expected package sha}"
BASE="${ROUTER_OPS_BASE:-/opt/router-ops}"
INCOMING="${ROUTER_STEP_INCOMING:-/home/ops/incoming}"
WORKFLOW_LIB="${ROUTER_STEP_WORKFLOW_LIB:-$BASE/lib/router-step-workflow.sh}"
FINALIZER="${ROUTER_STEP_FINALIZE_BIN:-$BASE/bin/router-step-finalize}"
SAFE_PAYLOAD="${ROUTER_PUBLIC_SAFE_PAYLOAD_BIN:-$BASE/bin/router-public-safe-payload}"
RUN_TARGET="${ROUTER_P28F1_RUN_TARGET:-$BUNDLE_ROOT/scripts/run-target.sh}"
release_env="$("$BASE/bin/router-release-contract" env --root "$BUNDLE_ROOT")"; eval "$release_env"
STEP_ID="$ROUTER_RELEASE_STEP_ID"
TARGET_PACKAGE_SHA256="$ROUTER_RELEASE_TARGET_PACKAGE_SHA256"
[[ "$EXPECTED_PACKAGE_SHA" == "$TARGET_PACKAGE_SHA256" ]]
TARGET_PACKAGE="$BUNDLE_ROOT/$ROUTER_RELEASE_TARGET_PACKAGE_PATH"
[[ "$(sha256sum "$TARGET_PACKAGE" | awk '{print $1}')" == "$TARGET_PACKAGE_SHA256" ]]
RUN_ID="${ROUTER_P28F1_RUN_ID:-$(date -u +%Y%m%d-%H%M%S)-$$}"
[[ "$RUN_ID" =~ ^[A-Za-z0-9-]+$ ]]
RUN_DIR="${ROUTER_STEP_RUN_DIR:-$BASE/state/step-runs/$STEP_ID/$RUN_ID}"
EVIDENCE_DIR="$RUN_DIR/evidence"; REPORT_DIR="$RUN_DIR/report"; PUBLIC_PAYLOAD="$RUN_DIR/public-payload"
CURRENT_FILE="$RUN_DIR/workflow-current.txt"; EVENTS_FILE="$RUN_DIR/workflow-events.tsv"; FINAL_ENV="$RUN_DIR/finalize.txt"
LOCK_FILE="${ROUTER_STEP_LOCK_FILE:-$BASE/state/locks/${STEP_ID}.lock}"
FINAL_CONFIG="${P28F1_OUTPUT_PATH:-/home/ops/incoming/SecretStudio-AWG-P28F1.conf}"
CURRENT_PHASE=preflight; CORE_CHANGE_COMPLETE=false; LATEST_ARCHIVE=not_created
source "$WORKFLOW_LIB"
mkdir -p "$RUN_DIR" "$EVIDENCE_DIR" "$REPORT_DIR" "$(dirname "$LOCK_FILE")"
exec 9>"$LOCK_FILE"; flock -n 9 || { echo RESULT=STOP_P28F1_STEP_ALREADY_RUNNING; echo STEP_WAS_NOT_STARTED=true; exit 75; }
router_step_workflow_init "$CURRENT_FILE" "$EVENTS_FILE" preflight export postcheck report_build finalization latest

build_report(){ python3 "$BUNDLE_ROOT/scripts/build-report.py" --bundle "$BUNDLE_ROOT" --run-dir "$RUN_DIR" --result "$1" --phase "$2" --rc "$3" --line "$4" --core-complete "$CORE_CHANGE_COMPLETE"; }
publish_report(){
  local args=() file
  for file in report.txt facts.json facts-public.html verify-public.html release-info.json installer.sha256 bundle-manifest.sha256 executed-step.sh executed-worker.sh workflow-current.txt workflow-events.tsv; do [[ ! -f "$REPORT_DIR/$file" ]] || args+=("$REPORT_DIR/$file" "$file"); done
  for file in preflight export postcheck; do [[ ! -f "$REPORT_DIR/$file.txt" ]] || args+=("$REPORT_DIR/$file.txt" "$file.txt"); done
  "$SAFE_PAYLOAD" "$PUBLIC_PAYLOAD" "${args[@]}"
  "$FINALIZER" --label step_p28f1_awg_private_export_r01 --payload-dir "$PUBLIC_PAYLOAD" --workflow-current "$CURRENT_FILE" --workflow-events "$EVENTS_FILE" --output-env "$FINAL_ENV" --expect-kind step-report
}
archive_latest(){
  router_step_archive_latest_python "$BASE" "$INCOMING" "$(date -u +%Y%m%d-%H%M%S)" > "$EVIDENCE_DIR/latest.txt" 2>&1
  cat "$EVIDENCE_DIR/latest.txt"
  grep -Fqx RESULT=PASS_ROUTER_STEP_ARCHIVE_LATEST "$EVIDENCE_DIR/latest.txt"
  LATEST_ARCHIVE="$(awk -F= '$1=="LATEST_ARCHIVE" {print substr($0,index($0,"=")+1)}' "$EVIDENCE_DIR/latest.txt" | tail -n1)"
  [[ -n "$LATEST_ARCHIVE" ]]
}
stop(){
  local line="$1" rc="$2" command="$3" phase="$CURRENT_PHASE"
  trap - ERR HUP INT TERM; set +e
  router_step_phase_fail "$phase" "line=$line rc=$rc" >/dev/null 2>&1
  if [[ "$CORE_CHANGE_COMPLETE" != true ]]; then rm -f -- "$FINAL_CONFIG" "$FINAL_CONFIG.tmp."* 2>/dev/null || true; fi
  if router_step_should_publish_stop; then if build_report STOP "$phase" "$rc" "$line"; then publish_report || echo STOP_REPORT_FINALIZATION=FAILED; else echo STOP_REPORT_BUILD=FAILED; fi; fi
  archive_latest || { echo STOP_LATEST_ARCHIVE=FAILED; cat "$EVIDENCE_DIR/latest.txt" 2>/dev/null; }
  router_step_emit_stop_evidence STOP_P28F1_R01_AWG_EXPORT "$phase" "$line" "$rc" "$command" VM121 "$CORE_CHANGE_COMPLETE" not_required "$LATEST_ARCHIVE" inspect_run_evidence_and_fix_export_path
  exit "$rc"
}
trap 'stop "$LINENO" "$?" "$BASH_COMMAND"' ERR; trap 'stop "$LINENO" 129 "signal HUP"' HUP; trap 'stop "$LINENO" 130 "signal INT"' INT; trap 'stop "$LINENO" 143 "signal TERM"' TERM
run_phase(){
  local phase="$1" expected="$2"
  CURRENT_PHASE="$phase"; router_step_phase_begin "$phase"
  "$RUN_TARGET" "$phase" "$RUN_ID" "$TARGET_PACKAGE_SHA256" > "$EVIDENCE_DIR/$phase.txt" 2>&1
  cat "$EVIDENCE_DIR/$phase.txt"
  grep -Fqx "RESULT=$expected" "$EVIDENCE_DIR/$phase.txt"
  router_step_phase_complete "$phase" "$expected"
}
run_phase preflight PASS_P28F1_R01_PREFLIGHT
CURRENT_PHASE=export; router_step_phase_begin export
"$BUNDLE_ROOT/scripts/vm121-apply.sh" "$TARGET_PACKAGE_SHA256" "$TARGET_PACKAGE" "$RUN_ID" > "$EVIDENCE_DIR/export.txt" 2>&1
cat "$EVIDENCE_DIR/export.txt"; grep -Fqx RESULT=PASS_P28F1_R01_EXPORT "$EVIDENCE_DIR/export.txt"
router_step_phase_complete export private_awg_config_written_0600_to_incoming
run_phase postcheck PASS_P28F1_R01_POSTCHECK
CORE_CHANGE_COMPLETE=true
CURRENT_PHASE=report_build; router_step_phase_begin report_build; build_report PASS none 0 0; router_step_phase_complete report_build secret_safe_evidence_ready
CURRENT_PHASE=finalization; router_step_phase_begin finalization; publish_report; router_step_phase_complete finalization canonical_report_http_verified
CURRENT_PHASE=latest; router_step_phase_begin latest; archive_latest; router_step_phase_complete latest fresh_latest_archive_verified
router_step_workflow_mark_complete; trap - ERR HUP INT TERM
cat "$FINAL_ENV"
echo "PRIVATE_CONFIG_PATH=$FINAL_CONFIG"
echo PRIVATE_CONFIG_MODE=600
echo PRIVATE_CONFIG_CONTENT_PUBLIC_EVIDENCE=false
echo MANUAL_CLIENT_IMPORT_REQUIRED=true
echo "LATEST_ARCHIVE=$LATEST_ARCHIVE"
echo CORE_CHANGE_COMPLETE=true
echo ROLLBACK_STATUS=not_required
echo RESULT=PASS_P28F1_R01_AWG_EXPORT
