import io

def rw(p, f):
    s = io.open(p, 'r', encoding='utf-8', newline='').read()
    nl = '\r\n' if '\r\n' in s else '\n'
    io.open(p, 'w', encoding='utf-8', newline='').write(f(s, nl))

# ---------------------------------------------------------------- main: pre-GO gate
MAIN_OLD = """# THE WINDOW OPENS HERE AND NOWHERE ELSE.
go "prepared acknowledgment verified\""""

MAIN_NEW = """# THE REMOVAL INSTRUMENT IS REQUIRED BEFORE THE WINDOW OPENS (doyle 2026-09-13).
# A run that cannot remove what it is about to create must never create it. The predecessor
# discovered its missing teardown at CLEANUP -- after the rules existed -- and could then only
# report PENDING and leave them for a human. Checking here costs no experimental time (this is
# still preparation) and turns that PENDING into a run that never started.
#
# THIS IS A PRECONDITION, NOT A PERMISSION. Verifying the instrument does not authorize its use
# any more than the PREPARED acknowledgment authorizes the setup; it establishes that the removal
# this run will owe is one it can actually hand over, pinned and reviewed.
if ! teardown_pin_verify pre-go; then
  die "the reviewed rule-removal instrument is not available (state=$TEARDOWN_PIN_STATE). The experimental window is NEVER OPENED: nothing is dispatched, nothing is created, and there is nothing to tear down. This is a refusal to start, not a failed run."
fi

# THE WINDOW OPENS HERE AND NOWHERE ELSE.
go "prepared acknowledgment verified and the reviewed removal instrument verified\""""

# ---------------------------------------------------------------- cleanup: dispatch gate
CL_OLD = """    if [ -z "$TEARDOWN_COMMAND_SHA256" ] || [ ! -f "$TEARDOWN_COMMAND_FILE" ]; then
      TEARDOWN_DISPATCH=WITHHELD_UNPINNED
      CLEANUP_VERDICT=PENDING
      record "TEARDOWN_WITHHELD - no product-emitted cleanup command is pinned. NO teardown is requested and NO command is reconstructed. Bootstrap-owned rules MAY REMAIN and their removal is PENDING/review; the state markers in $ST are left set deliberately."
      cfail "teardown not dispatched: the product-emitted cleanup command is not yet obtained, decoded, reviewed and pinned. This is a REFUSAL TO ACT, not a failed action."
    else
      tc_sha=$(sha256sum "$TEARDOWN_COMMAND_FILE" | cut -d" " -f1)
      if [ "$tc_sha" != "$TEARDOWN_COMMAND_SHA256" ]; then
        TEARDOWN_DISPATCH=WITHHELD_HASH_MISMATCH
        CLEANUP_VERDICT=PENDING
        cfail "the pinned teardown command file does not match its pin ($tc_sha != $TEARDOWN_COMMAND_SHA256). Different bytes are a different command: REFUSING to dispatch it."
      else
        TEARDOWN_DISPATCH=DISPATCHED
        record "TEARDOWN_COMMAND_PINNED sha256=$tc_sha - dispatching the product-emitted literal VERBATIM, exactly as the binary rendered it (never re-wrapped, re-typed or re-encoded)"
        handoff_request teardown \\
          "remove bootstrap-owned TCP admission created or possibly created by this run, using the PRODUCT-EMITTED cleanup command below VERBATIM" \\
          "$(cat "$TEARDOWN_COMMAND_FILE")"
      fi
    fi"""

CL_NEW = """    # VERIFIED A SECOND TIME, IMMEDIATELY BEFORE USE (doyle 2026-09-13). The pre-GO reading
    # was about the file as it stood then; these are the bytes about to be handed to an
    # elevated leg, and only a reading taken here can speak for them.
    if ! teardown_pin_verify pre-dispatch; then
      TEARDOWN_DISPATCH="WITHHELD_$TEARDOWN_PIN_STATE"
      CLEANUP_VERDICT=PENDING
      record "TEARDOWN_WITHHELD state=$TEARDOWN_PIN_STATE - NO teardown is requested and NO command is reconstructed or substituted. Bootstrap-owned rules MAY REMAIN and their removal is PENDING/review; the state markers in $ST are left set deliberately."
      cfail "teardown not dispatched (state=$TEARDOWN_PIN_STATE). This is a REFUSAL TO ACT, not a failed action, and a missing instrument is never replaced by a composed one."
    else
      TEARDOWN_DISPATCH=DISPATCHED
      record "TEARDOWN_COMMAND_PINNED reviewed_b64_sha256=$TEARDOWN_B64_SHA256 - dispatching the product-emitted literal VERBATIM, exactly as the binary rendered it (never re-wrapped, re-typed or re-encoded). It removes OWNED RULES ONLY: it stops no listener and removes no process."
      handoff_request teardown \\
        "remove bootstrap-owned TCP admission created or possibly created by this run, using the PRODUCT-EMITTED cleanup command below VERBATIM. It removes rules only -- do not stop any listener and do not kill any process on the strength of this request." \\
        "$(cat "$TEARDOWN_COMMAND_FILE")"
    fi"""

# ---------------------------------------------------------------- cleanup: post-removal check
POST_OLD = """      local verdict=0 absent=0 valid=0
      grep -q 'LAN_FIREWALL_CLEAN' "$HO_OUT" 2>/dev/null && verdict=1
      grep -q 'tag=cleanup-teardown-post .* subj_group=0 subj_29470=0' "$R/census.log" && absent=1
      grep -q 'tag=cleanup-teardown-post .* valid=YES' "$R/census.log" && valid=1
      record "TEARDOWN_CHECK receipt_exit=$t_rc census_exit=$c_rc clean_verdict=$verdict named_rules_absent=$absent census_valid=$valid"
      if [ "$t_rc" -eq 0 ] && [ "$c_rc" -eq 0 ] && [ "$verdict" -eq 1 ] && [ "$absent" -eq 1 ] && [ "$valid" -eq 1 ]; then
        record "TEARDOWN_VERIFIED — zero teardown exit AND a successful census AND the product's own LAN_FIREWALL_CLEAN verdict AND the owned named rules measured ABSENT"
        CLEANUP_VERDICT=VERIFIED
      else
        cfail "TEARDOWN NOT VERIFIED (receipt_exit=$t_rc census_exit=$c_rc clean_verdict=$verdict absent=$absent census_valid=$valid). Owned rules MAY REMAIN. The state marker is left set deliberately."
      fi"""

POST_NEW = """      local verdict=0 absent=0 valid=0
      grep -q 'LAN_FIREWALL_CLEAN' "$HO_OUT" 2>/dev/null && verdict=1
      grep -q 'tag=cleanup-teardown-post .* subj_group=0 subj_29470=0' "$R/census.log" && absent=1
      grep -q 'tag=cleanup-teardown-post .* valid=YES' "$R/census.log" && valid=1
      # INDEPENDENT POST-REMOVAL CHECK (doyle 2026-09-13). Everything above is either the
      # product's own verdict -- the claim under test -- or a census that counts ActiveStore
      # rules by GROUP and PORT. Neither can say WHICH owned name is gone, and neither reads
      # PersistentStore at all, so a removal that took one rule and failed on the other, or that
      # emptied PersistentStore while leaving ActiveStore residue, could pass both. This probe
      # addresses each owned name by InstanceID in EACH store and is the reading that decides.
      removal_check
      record "TEARDOWN_CHECK receipt_exit=$t_rc census_exit=$c_rc clean_verdict=$verdict named_rules_absent=$absent census_valid=$valid independent_removal=$REMOVAL_CHECK"
      if [ "$t_rc" -eq 0 ] && [ "$c_rc" -eq 0 ] && [ "$verdict" -eq 1 ] && [ "$absent" -eq 1 ] && [ "$valid" -eq 1 ] && [ "$REMOVAL_CHECK" = CONFIRMED ]; then
        record "TEARDOWN_VERIFIED — zero teardown exit AND a successful census AND the product's own LAN_FIREWALL_CLEAN verdict AND the owned named rules measured ABSENT by an INDEPENDENT per-name, per-store probe"
        CLEANUP_VERDICT=VERIFIED
      else
        CLEANUP_VERDICT=PENDING
        cfail "TEARDOWN NOT VERIFIED (receipt_exit=$t_rc census_exit=$c_rc clean_verdict=$verdict absent=$absent census_valid=$valid independent_removal=$REMOVAL_CHECK). Owned rules MAY REMAIN; removal is PENDING/review and is NOT retried. The state marker is left set deliberately."
      fi"""

def mn(s, nl):
    o = MAIN_OLD.replace('
', nl)
    assert o in s, 'main gate'
    return s.replace(o, MAIN_NEW.replace('
', nl), 1)


rw('_part_main.sh', mn)


def cl(s, nl):
    o = CL_OLD.replace('\n', nl)
    assert o in s, 'cleanup dispatch'
    s = s.replace(o, CL_NEW.replace('\n', nl), 1)
    p = POST_OLD.replace('\n', nl)
    assert p in s, 'post-removal'
    return s.replace(p, POST_NEW.replace('\n', nl), 1)


rw('_part_cleanup.sh', cl)
print('main gate + dispatch + post-removal written')
