import io

RULEPROBE_SHA = '1e007cdc84582b4739137b06505b7e2f242581f6dafc8546a5ae89be2cf11756'

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

HDR_OLD = """TEARDOWN_COMMAND_SHA256=''        # UNPINNED. Fill BOTH or neither; a file without its hash is
                                  # refused exactly like no file at all."""

HDR_NEW = """# PINNED 2026-09-13 (doyle F3VCR5KO): the emitted payload is ACCEPTED as the reviewed
# RULE-REMOVAL CANDIDATE. Acceptance is not permission to execute it -- it is what would make a
# dispatch under a future grant legitimate at all.
TEARDOWN_B64_FILE="$PRESERVED_D2/d3/decoded-todlando/d3-payload.b64"
                                  # THE REVIEWED PAYLOAD ITSELF, at its permanent path. The
                                  # authority is doyle's pin below, not this driver's opinion.
TEARDOWN_B64_SHA256='416280dbece2601203c74c3f8e2c46e13009125fa5870166894e079329fb1d43'
# WHY TWO FILES AND ONE PIN. The bytes dispatched to an elevated leg must be the PRODUCT'S OWN
# emitted line, never one this driver assembles; the bytes REVIEWED are the base64 payload inside
# it. So the literal is kept verbatim in TEARDOWN_COMMAND_FILE and the check is that the payload
# INSIDE that literal is byte-for-byte the reviewed file, which in turn hashes to the pin above.
# Nothing is composed, and nothing unreviewed can ride along inside a literal that merely looks
# right.
RULE_PROBE="$PRESERVED_D2/rule-probe.ps1"
RULE_PROBE_SHA256='__RULEPROBE__'
                                  # THE INDEPENDENT POST-REMOVAL CHECK. The product reporting its
                                  # own success is the claim under test, and the census counts
                                  # ActiveStore rules by GROUP and PORT -- neither can say which
                                  # owned NAME is gone, nor anything at all about PersistentStore.
                                  # This probe addresses each name by InstanceID in each store.
                                  # It is evidence, so it is pinned like any other instrument.
TEARDOWN_PIN_STATE=UNCHECKED      # set by teardown_pin_verify; reported whatever it says"""

CLEAN_ANCHOR = """CLEANUP_EPOCH=0
CLEANUP_STOP_STATE=NOT_REACHED   # which gate outcome step 1 took (IR-124)
TEARDOWN_DISPATCH=NOT_REACHED    # whether a teardown command was dispatched, and why not"""

CLEAN_ADD = r"""
REMOVAL_CHECK=NOT_REACHED        # the INDEPENDENT post-removal reading, by name and by store
# ---- THE PINNED REMOVAL INSTRUMENT, VERIFIED TWICE (doyle 2026-09-13) --------
# Once BEFORE GO -- a run that cannot remove what it is about to create must never open the
# window -- and again immediately BEFORE USE, because the file can change in between and the
# first reading would then be about bytes nobody is dispatching. Each call names its context so
# the two readings cannot be mistaken for one another in the ledger.
#
# WHAT THE INSTRUMENT IS, read from the decoded payload: it removes the two OWNED rules from
# PersistentStore after asserting each rule's group and TCP protocol, then re-reads BOTH stores
# and throws if anything remains. IT STOPS NO LISTENER AND REMOVES NO PROCESS. The listener and
# process disposition stays exactly where it was -- a separate, observation-gated question that
# this command neither answers nor affects.
teardown_pin_verify() { # CONTEXT -> 0 when the reviewed instrument is present and intact
  local ctx="$1" sha b64
  TEARDOWN_PIN_STATE=UNCHECKED
  if [ -z "$TEARDOWN_B64_SHA256" ]; then
    TEARDOWN_PIN_STATE=UNPINNED
    record "TEARDOWN_PIN($ctx)=UNPINNED - no reviewed pin is configured. An empty pin is this run saying it has no authorized command to hand an elevated leg."
    return 1
  fi
  if [ ! -f "$TEARDOWN_B64_FILE" ]; then
    TEARDOWN_PIN_STATE=MISSING_REVIEWED_PAYLOAD
    record "TEARDOWN_PIN($ctx)=MISSING_REVIEWED_PAYLOAD [$TEARDOWN_B64_FILE] - the reviewed bytes are not where the pin says they live."
    return 1
  fi
  if [ ! -f "$TEARDOWN_COMMAND_FILE" ]; then
    TEARDOWN_PIN_STATE=MISSING_COMMAND_LITERAL
    record "TEARDOWN_PIN($ctx)=MISSING_COMMAND_LITERAL [$TEARDOWN_COMMAND_FILE] - the product's emitted line is absent, and this driver does not compose one."
    return 1
  fi
  sha=$(sha256sum "$TEARDOWN_B64_FILE" | cut -d' ' -f1)
  if [ "$sha" != "$TEARDOWN_B64_SHA256" ]; then
    TEARDOWN_PIN_STATE=REVIEWED_PAYLOAD_HASH_MISMATCH
    record "TEARDOWN_PIN($ctx)=REVIEWED_PAYLOAD_HASH_MISMATCH measured=$sha pinned=$TEARDOWN_B64_SHA256 - different bytes are a different command."
    return 1
  fi
  b64=$(sed -n 's/.*-EncodedCommand \([A-Za-z0-9+/=]*\).*/\1/p' "$TEARDOWN_COMMAND_FILE")
  if [ -z "$b64" ]; then
    TEARDOWN_PIN_STATE=LITERAL_CARRIES_NO_ENCODEDCOMMAND
    record "TEARDOWN_PIN($ctx)=LITERAL_CARRIES_NO_ENCODEDCOMMAND - the literal is not the shape the reviewed payload rides in; REFUSED rather than guessed at."
    return 1
  fi
  if ! printf '%s' "$b64" | cmp -s - "$TEARDOWN_B64_FILE"; then
    TEARDOWN_PIN_STATE=LITERAL_PAYLOAD_DIFFERS_FROM_REVIEWED
    record "TEARDOWN_PIN($ctx)=LITERAL_PAYLOAD_DIFFERS_FROM_REVIEWED - what was reviewed is not what would be dispatched: REFUSED."
    return 1
  fi
  TEARDOWN_PIN_STATE=VERIFIED
  record "TEARDOWN_PIN($ctx)=VERIFIED reviewed_b64_sha256=$sha - the dispatchable literal carries the reviewed payload byte for byte"
  return 0
}"""


def hdr(s, nl):
    old = HDR_OLD.replace('\n', nl)
    new = HDR_NEW.replace('__RULEPROBE__', RULEPROBE_SHA).replace('\n', nl)
    assert old in s, 'header anchor'
    return s.replace(old, new, 1)


def clean(s, nl):
    a = CLEAN_ANCHOR.replace('\n', nl)
    assert a in s, 'cleanup anchor'
    return s.replace(a, a + CLEAN_ADD.replace('\n', nl), 1)


rw('_part1_header.sh', hdr)
rw('_part_cleanup.sh', clean)
print('header + verifier written')
