#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

STEP_ID='STEP_050M07R20B_R07_HTML_HELPER_INTERPRETER_SAFE_STEP_REPORT_FINALIZATION_CONTINUATION'
RESULT='STOP_R20B_R07_NOT_STARTED'
STOP_REASON='none'
CURRENT_PHASE='initializing'
COPY_VERIFY='FAIL'
HTTP_VERIFY_PASS=false
PUBLICATION_BARRIER=none
STEP_REPORT_URL=''
FACTS_URL=''
VERIFY_URL=''
ROLLBACK_URL=''
R04_DIR=''
R06_DIR=''

BUNDLE_DIR="$(cd "$(dirname "$0")" && pwd -P)"
SELF="$(readlink -f "$0")"
BUNDLE_ZIP="${BUNDLE_ZIP:?BUNDLE_ZIP is required}"
EXPECTED_BUNDLE_SHA256="${EXPECTED_BUNDLE_SHA256:?EXPECTED_BUNDLE_SHA256 is required}"
EXPECTED_INSTALLER_SHA256="${EXPECTED_INSTALLER_SHA256:?EXPECTED_INSTALLER_SHA256 is required}"
BASE="${ROUTER_OPS_BASE:-/opt/router-ops}"
WORKFLOW_LIB="$BASE/lib/router-step-workflow.sh"
TS="$(date -u +%Y%m%d-%H%M%S)"
STEP_DIR="$BASE/steps/${TS}_${STEP_ID}"
mkdir -p "$STEP_DIR/components"
chmod 700 "$STEP_DIR"
STOP_GUARD_DIR="$STEP_DIR/.stop-handler-active"
STEP_FILE="$STEP_DIR/step-code.sh"
BUNDLE_COPY="$STEP_DIR/$(basename "$BUNDLE_ZIP")"
cp -a "$SELF" "$STEP_FILE"
chmod 700 "$STEP_FILE"
cp -a "$BUNDLE_ZIP" "$BUNDLE_COPY"

REPORT="$STEP_DIR/report.txt"
FACTS="$STEP_DIR/facts.json"
VERIFY="$STEP_DIR/verify.txt"
ROLLBACK="$STEP_DIR/rollback.sh"
MAIN_LOG="$STEP_DIR/main.log"
PROGRESS="$STEP_DIR/progress.log"
TRANSFER="$STEP_DIR/transfer-verify.txt"
PHASE_CURRENT="$STEP_DIR/phase-current.env"
PHASE_EVENTS="$STEP_DIR/phase-events.log"
COMPONENTS="$STEP_DIR/components"

exec 3>&1
exec >>"$MAIN_LOG" 2>&1

progress() {
    printf '>>> [%s] %s\n' "$(date '+%F %T')" "$*" | tee -a "$PROGRESS" >&3
}

field() {
    local file
    local key
    file="$1"
    key="$2"
    awk -F= -v k="$key" '$1==k{v=substr($0,index($0,"=")+1)} END{print v}' "$file"
}

emit_final() {
    local item
    for item in \
        "RESULT=$RESULT" \
        "STEP_REPORT_URL=${STEP_REPORT_URL:-PENDING_NOT_PUBLISHED}" \
        "PROJECT_SOURCE_POST_URL=${PROJECT_SOURCE_POST_URL:-PENDING_NOT_PUBLISHED}" \
        "PROJECT_SOURCE_POST_FILE_URL=${PROJECT_SOURCE_POST_FILE_URL:-PENDING_NOT_PUBLISHED}" \
        "LOCAL_M07_PLAN_URL=$LOCAL_M07_PLAN_URL" \
        "GLOBAL_PROJECT_PLAN_URL=$GLOBAL_PROJECT_PLAN_URL" \
        "ACCESS_MAP_URL=$ACCESS_MAP_URL" \
        "VM100_PUBLIC_URL=$VM100_PUBLIC_URL" \
        "VM101_PUBLIC_URL=$VM101_PUBLIC_URL" \
        "VM121_PUBLIC_URL=$VM121_PUBLIC_URL" \
        "VM101_MODEL_URL=$VM101_MODEL_URL" \
        "VM101_METHODS_URL=$VM101_METHODS_URL" \
        "VM130_SOURCE_URL=${VM130_SOURCE_URL:-PENDING_NOT_PUBLISHED}" \
        "LATEST_ROOT_URL=$LATEST_ROOT_URL" \
        "OLD_ROOT_URL=$OLD_ROOT_URL" \
        "FACTS_URL=${FACTS_URL:-PENDING_NOT_PUBLISHED}" \
        "VERIFY_URL=${VERIFY_URL:-PENDING_NOT_PUBLISHED}" \
        "ROLLBACK_URL=${ROLLBACK_URL:-PENDING_NOT_PUBLISHED}" \
        "PUBLIC_OBJECT_KIND=step-report" \
        "PREVIOUS_MOVED_COUNT=0" \
        "COPY_VERIFY=$COPY_VERIFY" \
        "STEP_SHA256=$(sha256sum "$STEP_FILE" | awk '{print $1}')" \
        "HTTP_VERIFY_PASS=$HTTP_VERIFY_PASS" \
        "RUNTIME_IMPACT=false" \
        "R20B_R04_COMPLETED_PHASES_REPEATED=false" \
        "VM130_SOURCE_PUBLICATION_REPEATED=false" \
        "PROJECT_SOURCE_PUBLICATION_REPEATED=false" \
        "EXTERNAL_HTTP_VERIFICATION_REPEATED=false" \
        "VM101_RUNTIME_CHANGED=false" \
        "INVENTORY_REPEATED=false"
    do
        printf '%s\n' "$item" >&3
    done
}

publish_stop_report() {
    set +e
    if [[ -n "$R04_DIR" && -d "$R04_DIR" ]]; then
        R20B_R07_STEP_ID="$STEP_ID" \
        R20B_R07_COPY_VERIFY="$COPY_VERIFY" \
        R20B_R07_STOP_RESULT="$RESULT" \
        R20B_R07_STOP_REASON="$STOP_REASON" \
        R20B_R07_CURRENT_PHASE="$CURRENT_PHASE" \
        bash "$BUNDLE_DIR/scripts/r20b-r07-finalize.sh" \
            "$STEP_DIR" "$R04_DIR" "$R06_DIR" "$BUNDLE_DIR" stop >"$COMPONENTS/stop-finalization.log" 2>&1
        stop_finalize_rc=$?
        if [[ "$stop_finalize_rc" -eq 0 ]]; then
            STEP_REPORT_URL="$(field "$COMPONENTS/stop-finalization.log" PUBLIC_URL)"
            FACTS_URL="$(field "$COMPONENTS/stop-finalization.log" FACTS_URL)"
            VERIFY_URL="$(field "$COMPONENTS/stop-finalization.log" VERIFY_URL)"
            ROLLBACK_URL="$(field "$COMPONENTS/stop-finalization.log" ROLLBACK_URL)"
            PUBLICATION_BARRIER=verified
            HTTP_VERIFY_PASS=true
        fi
    fi
    set -e
}

stop() {
    local result
    local reason
    local rc
    result="$1"
    reason="$2"
    rc="${3:-1}"
    trap - ERR
    if ! mkdir "$STOP_GUARD_DIR" 2>/dev/null; then
        exit "$rc"
    fi
    RESULT="$result"
    STOP_REASON="$reason"
    router_step_phase_fail "$CURRENT_PHASE" "$reason" >/dev/null 2>&1 || true
    publish_stop_report || true
    emit_final
    exit "$rc"
}

trap 'stop STOP_R20B_R07_UNEXPECTED_ERROR "phase=$CURRENT_PHASE line=$LINENO rc=$?" 1' ERR

source "$BUNDLE_DIR/plans/current-links.env"
source "$WORKFLOW_LIB"

router_step_workflow_init \
    "$PHASE_CURRENT" \
    "$PHASE_EVENTS" \
    transfer_verification \
    continuation_preflight \
    external_http_verification \
    step_report_publication

CURRENT_PHASE='transfer_verification'
router_step_phase_begin transfer_verification none
progress transfer_verification

actual_zip="$(sha256sum "$BUNDLE_COPY" | awk '{print $1}')"
actual_installer="$(sha256sum "$STEP_FILE" | awk '{print $1}')"
[[ "$actual_zip" == "$EXPECTED_BUNDLE_SHA256" ]] || stop STOP_COPY_OR_TRANSFER_ERROR zip_sha_mismatch 20
[[ "$actual_installer" == "$EXPECTED_INSTALLER_SHA256" ]] || stop STOP_COPY_OR_TRANSFER_ERROR installer_sha_mismatch 20

(
    cd "$BUNDLE_DIR"
    sha256sum -c manifest.sha256
) >"$STEP_DIR/manifest.log"

BUNDLE_ROOT="$BUNDLE_DIR" "$BASE/bin/router-bundle-gate" "$BUNDLE_DIR" >"$STEP_DIR/bundle-gate.log"
grep -qx 'RESULT=PASS_ROUTER_BUNDLE_GATE_R19' "$STEP_DIR/bundle-gate.log" || stop STOP_COPY_OR_TRANSFER_ERROR r19_gate_marker_missing 20
grep -qx 'RESULT=PASS_ROUTER_BUNDLE_GATE_R20' "$STEP_DIR/bundle-gate.log" || stop STOP_COPY_OR_TRANSFER_ERROR r20_gate_marker_missing 20
grep -qx 'RESULT=PASS_ROUTER_BUNDLE_GATE' "$STEP_DIR/bundle-gate.log" || stop STOP_COPY_OR_TRANSFER_ERROR generic_gate_marker_missing 20

COPY_VERIFY=PASS
cat >"$TRANSFER" <<'R20B_R07_TRANSFER'
COPY_VERIFY=PASS
MANIFEST_VERIFY=PASS
SYNTAX_VERIFY=PASS
FIXTURE_VERIFY=PASS
R19_POLICY_VERIFY=PASS
R20_POLICY_VERIFY=PASS
R20B_R07_TRANSFER
router_step_phase_complete transfer_verification complete

CURRENT_PHASE='continuation_preflight'
router_step_phase_begin continuation_preflight none
progress continuation_preflight

[[ "$(hostname)" == router-ops ]] || stop STOP_R20B_R07_WRONG_HOST "$(hostname)" 21

R04_DIR="$(
    find "$BASE/steps" \
        -mindepth 1 \
        -maxdepth 1 \
        -type d \
        -name '*_STEP_050M07R20B_R04_ALL_PAYLOAD_COUNT_FIXTURES_PYCACHE_TOLERANT_AND_FINALIZATION_CONTINUATION' \
        -print |
    LC_ALL=C sort |
    tail -n 1
)"
[[ -n "$R04_DIR" && -d "$R04_DIR" ]] || stop STOP_R20B_R07_R04_EVIDENCE_MISSING none 21

for expected in \
    'transfer_verification=complete' \
    'continuation_preflight=complete' \
    'compatibility_fix=complete' \
    'target_postcheck=complete' \
    'vm130_source_publication=complete' \
    'project_source_publication=complete' \
    'external_http_verification=complete' \
    'step_report_publication=failed'
do
    grep -qx "$expected" "$R04_DIR/phase-current.env" || stop STOP_R20B_R07_R04_PHASE_MISMATCH "$expected" 21
done

for required in \
    "$R04_DIR/report.txt" \
    "$R04_DIR/verify.txt" \
    "$R04_DIR/rollback.sh" \
    "$R04_DIR/main.log" \
    "$R04_DIR/phase-current.env" \
    "$R04_DIR/phase-events.log"
do
    [[ -f "$required" ]] || stop STOP_R20B_R07_R04_EVIDENCE_FILE_MISSING "$required" 21
done

VM130_SOURCE_URL="$(field "$R04_DIR/report.txt" VM130_SOURCE_URL)"
PROJECT_SOURCE_POST_URL="$(field "$R04_DIR/report.txt" PROJECT_SOURCE_POST_URL)"
PROJECT_SOURCE_POST_FILE_URL="$(field "$R04_DIR/report.txt" PROJECT_SOURCE_POST_FILE_URL)"

[[ "$VM130_SOURCE_URL" == "$EXPECTED_R04_VM130_SOURCE_URL" ]] || stop STOP_R20B_R07_R04_VM130_SOURCE_URL_MISMATCH "$VM130_SOURCE_URL" 21
[[ "$PROJECT_SOURCE_POST_URL" == "$EXPECTED_R04_PROJECT_SOURCE_POST_URL" ]] || stop STOP_R20B_R07_R04_PROJECT_SOURCE_URL_MISMATCH "$PROJECT_SOURCE_POST_URL" 21
[[ "$PROJECT_SOURCE_POST_FILE_URL" == "$EXPECTED_R04_PROJECT_SOURCE_POST_FILE_URL" ]] || stop STOP_R20B_R07_R04_PROJECT_SOURCE_FILE_URL_MISMATCH "$PROJECT_SOURCE_POST_FILE_URL" 21

grep -Fq 'SyntaxError: unterminated string literal' "$R04_DIR/main.log" || stop STOP_R20B_R07_R04_FAILURE_SIGNATURE_MISMATCH none 21

R06_DIR="$(
    find "$BASE/steps" \
        -mindepth 1 \
        -maxdepth 1 \
        -type d \
        -name '*_STEP_050M07R20B_R06_EXTRACTION_MODE_SAFE_STEP_REPORT_FINALIZATION_CONTINUATION' \
        -print |
    LC_ALL=C sort |
    tail -n 1
)"
[[ -n "$R06_DIR" && -d "$R06_DIR" ]] || stop STOP_R20B_R07_R06_EVIDENCE_MISSING none 21
for expected in \
    'transfer_verification=complete' \
    'continuation_preflight=complete' \
    'external_http_verification=complete' \
    'step_report_publication=failed'
do
    grep -qx "$expected" "$R06_DIR/phase-current.env" || stop STOP_R20B_R07_R06_PHASE_MISMATCH "$expected" 21
done
for required in "$R06_DIR/main.log" "$R06_DIR/phase-current.env" "$R06_DIR/phase-events.log"; do
    [[ -f "$required" ]] || stop STOP_R20B_R07_R06_EVIDENCE_FILE_MISSING "$required" 21
done

router_step_phase_complete continuation_preflight complete

CURRENT_PHASE='external_http_verification'
router_step_phase_begin external_http_verification reused_from_r04_no_http
progress external_http_verification_reused_from_r04
router_step_phase_complete external_http_verification reused_from_r04_no_http

CURRENT_PHASE='step_report_publication'
router_step_phase_begin step_report_publication none
progress step_report_publication

R20B_R07_STEP_ID="$STEP_ID" \
R20B_R07_COPY_VERIFY="$COPY_VERIFY" \
R20B_R07_HTTP_VERIFY_PASS=true \
R20B_R07_PUBLICATION_BARRIER=verified \
bash "$BUNDLE_DIR/scripts/r20b-r07-finalize.sh" \
    "$STEP_DIR" "$R04_DIR" "$R06_DIR" "$BUNDLE_DIR" pass >"$COMPONENTS/finalization.log"

grep -qx 'RESULT=PASS_R20B_R07_FINALIZATION_PATH' "$COMPONENTS/finalization.log" || stop STOP_R20B_R07_FINALIZATION_CONTRACT marker 22

STEP_REPORT_URL="$(field "$COMPONENTS/finalization.log" PUBLIC_URL)"
FACTS_URL="$(field "$COMPONENTS/finalization.log" FACTS_URL)"
VERIFY_URL="$(field "$COMPONENTS/finalization.log" VERIFY_URL)"
ROLLBACK_URL="$(field "$COMPONENTS/finalization.log" ROLLBACK_URL)"
RESULT='PASS_R20B_DEGRADED_POOL_DESIGN_AND_VM130_POLICY_HARDENED'
STOP_REASON='none'
CURRENT_PHASE='complete'
PUBLICATION_BARRIER=verified
HTTP_VERIFY_PASS=true

trap - ERR
emit_final
