#!/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_P29H1_RUN_TARGET:-$BUNDLE_ROOT/scripts/run-target.sh}"
eval "$("$BASE/bin/router-release-contract" env --root "$BUNDLE_ROOT")"
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_P29H1_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}"
CURRENT_PHASE=preflight; CORE_CHANGE_COMPLETE=false; ROLLBACK_STATUS=not_applicable; 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_P29H1_STEP_ALREADY_RUNNING; echo STEP_WAS_NOT_STARTED=true; exit 75; }
router_step_workflow_init "$CURRENT_FILE" "$EVENTS_FILE" preflight acceptance 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" --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 preflight acceptance postcheck; do
    [[ ! -f "$REPORT_DIR/$file.txt" ]] || args+=("$REPORT_DIR/$file.txt" "$file.txt")
  done
  "$SAFE_PAYLOAD" "$PUBLIC_PAYLOAD" "${args[@]}"
  "$FINALIZER" --label step_vm121_p29h1_real_payment_acceptance_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
  ROLLBACK_STATUS=not_applicable
  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; }
  local next=inspect_preflight_and_retry_same_step
  if grep -Fqx P29H1_EXTERNAL_PROVIDER_WRITE_OBSERVED=true "$EVIDENCE_DIR/acceptance.txt" 2>/dev/null; then
    next=preserve_payment_history_and_reconcile_same_provider_payment
  fi
  router_step_emit_stop_evidence STOP_P29H1_R01_VM121_YOOKASSA_REAL_PAYMENT_ACCEPTANCE "$phase" "$line" "$rc" "$command" VM121 "$CORE_CHANGE_COMPLETE" "$ROLLBACK_STATUS" "$LATEST_ARCHIVE" "$next"
  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=preflight
router_step_phase_begin preflight
"$RUN_TARGET" preflight "$RUN_ID" "$TARGET_PACKAGE_SHA256" > "$EVIDENCE_DIR/preflight.txt" 2>&1
cat "$EVIDENCE_DIR/preflight.txt"
grep -Fqx RESULT=PASS_P29H1_R01_PREFLIGHT "$EVIDENCE_DIR/preflight.txt"
router_step_phase_complete preflight fresh_target_user_live_provider_and_zero_payment_history_verified
CURRENT_PHASE=acceptance
router_step_phase_begin acceptance
"$RUN_TARGET" acceptance "$RUN_ID" "$TARGET_PACKAGE_SHA256" 2>&1 | tee "$EVIDENCE_DIR/acceptance.txt"
grep -Fqx RESULT=PASS_P29H1_R01_ACCEPTANCE "$EVIDENCE_DIR/acceptance.txt"
CORE_CHANGE_COMPLETE=true
router_step_phase_complete acceptance one_controlled_real_payment_authoritatively_succeeded_and_fiscalized
CURRENT_PHASE=postcheck
router_step_phase_begin postcheck
"$RUN_TARGET" postcheck "$RUN_ID" "$TARGET_PACKAGE_SHA256" > "$EVIDENCE_DIR/postcheck.txt" 2>&1
cat "$EVIDENCE_DIR/postcheck.txt"
grep -Fqx RESULT=PASS_P29H1_R01_POSTCHECK "$EVIDENCE_DIR/postcheck.txt"
router_step_phase_complete postcheck provider_ledger_entitlement_and_configuration_mirror_reverified
CURRENT_PHASE=report_build
router_step_phase_begin report_build
build_report PASS none 0 0
router_step_phase_complete report_build p29h1_acceptance_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 "LATEST_ARCHIVE=$LATEST_ARCHIVE"
echo CORE_CHANGE_COMPLETE=true
echo ROLLBACK_STATUS=not_applicable
echo RESULT=PASS_P29H1_R01_VM121_YOOKASSA_REAL_PAYMENT_ACCEPTANCE
