#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUNDLE_ROOT="${BUNDLE_ROOT:-$(cd "$SCRIPT_DIR/.." && pwd)}"; export BUNDLE_ROOT
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}"
MACHINE_CLOSE="${ROUTER_MACHINE_CLOSE_SAFE:-$BASE/bin/router-machine-close-safe}"
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"
TARGET_TREE='be2358a31a1ea149d2d11d1875a893be6be7c6f5'; TARGET_COMMIT='00a4d71a3fcc3530a01f616a62c3f4b9163eb9eb'; TARGET_FILE_COUNT=41
RUN_ID="${ROUTER_B5A_R03_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"; CURRENT_PHASE=source_publish
LOCK_FILE="${ROUTER_STEP_LOCK_FILE:-$BASE/state/locks/${STEP_ID}.lock}"
CORE_CHANGE_COMPLETE=true; ROLLBACK_STATUS=preserved_accepted_core; LATEST_ARCHIVE=not_created
TRANSPORT_DIR="$BUNDLE_ROOT/scripts/transport"; [[ -x "$TRANSPORT_DIR/ssh" ]]
export PATH="$TRANSPORT_DIR:$PATH"
source "$WORKFLOW_LIB"
mkdir -p "$RUN_DIR" "$EVIDENCE_DIR" "$REPORT_DIR" "$(dirname "$LOCK_FILE")"
exec 9>"$LOCK_FILE"
flock -n 9 || { echo RESULT=STOP_R03_STEP_ALREADY_RUNNING; echo STEP_WAS_NOT_STARTED=true; exit 75; }
router_step_workflow_init "$CURRENT_FILE" "$EVENTS_FILE" source_publish report_build finalization latest

build_report() {
  local result="$1" phase="$2" rc="$3" line="$4"
  python3 "$BUNDLE_ROOT/scripts/build-report.py" --bundle "$BUNDLE_ROOT" --run-dir "$RUN_DIR" --result "$result" --phase "$phase" --rc "$rc" --line "$line" --core-complete "$CORE_CHANGE_COMPLETE" --rollback-status "$ROLLBACK_STATUS"
}
publish_report() {
  local args=() file
  for file in report.txt facts.json facts-public.html verify-public.html rollback-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 source-publish; do
    [[ ! -f "$REPORT_DIR/$file.txt" ]] || args+=("$REPORT_DIR/$file.txt" "$file.txt")
  done
  "$SAFE_PAYLOAD" "$PUBLIC_PAYLOAD" "${args[@]}"
  "$FINALIZER" --label step_vm100_b5a_selector_cpu_r03_source_close --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 || return $?
  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 -n 1)"
  [[ -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 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
  router_step_emit_stop_evidence STOP_B5A_R03_SOURCE_CLOSE "$phase" "$line" "$rc" "$command" VM100 "$CORE_CHANGE_COMPLETE" "$ROLLBACK_STATUS" "$LATEST_ARCHIVE" inspect_r03_evidence_continue_source_close_only
  echo CONTINUATION_REQUIRED=true
  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

CURRENT_PHASE=source_publish
router_step_phase_begin source_publish
if "$BUNDLE_ROOT/scripts/read-only-guard.sh" "$EVIDENCE_DIR/source-check.txt" > "$EVIDENCE_DIR/guard.txt" 2>&1; then child_rc=0; else child_rc=$?; fi
cat "$EVIDENCE_DIR/guard.txt"
test "$child_rc" -eq 0
grep -Fqx RESULT=PASS_B5A_R03_READONLY_GUARD "$EVIDENCE_DIR/guard.txt"
# Re-enter only the originally unfinished source_publish phase; the upstream
# machine publisher does NOTHING_TO_PUBLISH for a commit already on GitHub.
if "$MACHINE_CLOSE" vm100 'STEP_050M07_B5A_R02_VM100_SELECTOR_CPU optimized selector source publication continuation' > "$EVIDENCE_DIR/source-publish.txt" 2>&1; then child_rc=0; else child_rc=$?; fi
cat "$EVIDENCE_DIR/source-publish.txt"
test "$child_rc" -eq 0
grep -Fqx 'RESULT=PASS_ROUTER_MACHINE_CLOSE' "$EVIDENCE_DIR/source-publish.txt"
grep -Fqx "COMMIT=$TARGET_COMMIT" "$EVIDENCE_DIR/source-publish.txt"
grep -Fqx "TREE=$TARGET_TREE" "$EVIDENCE_DIR/source-publish.txt"
grep -Fqx "GIT_FILE_COUNT=$TARGET_FILE_COUNT" "$EVIDENCE_DIR/source-publish.txt"
grep -Fqx 'NO_CHANGES=true' "$EVIDENCE_DIR/source-publish.txt"
grep -Fqx 'COMMIT_CREATED=false' "$EVIDENCE_DIR/source-publish.txt"
router_step_phase_complete source_publish accepted_vm100_tree_00a4d71_closed_and_vm103_mirrored
CURRENT_PHASE=report_build; router_step_phase_begin report_build
build_report PASS none 0 0
router_step_phase_complete report_build prior_core_evidence_continuation_report_ready
CURRENT_PHASE=finalization; router_step_phase_begin finalization
publish_report
router_step_phase_complete finalization canonical_step_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"
cat "$REPORT_DIR/report.txt"
echo RESULT=PASS_B5A_R03_VM100_SELECTOR_SOURCE_CLOSE
echo "RUN_DIR=$RUN_DIR"
echo "LATEST_ARCHIVE=$LATEST_ARCHIVE"
