import io, sys, subprocess

P = 'd2-integration-receipt.md'
s = io.open(P, encoding='utf-8').read()


def sub(old, new, note):
    global s
    n = s.count(old)
    if n != 1:
        sys.exit('ANCHOR %r matched %d times (%s)' % (old[:70], n, note))
    s = s.replace(old, new)
    print('ok  ' + note)


def sha(path):
    out = subprocess.check_output(['sha256sum', path]).decode()
    return out.split()[0]


# The subject row named a driver that has been superseded twice. Replace it with the current
# subject AND its preserved lineage, so the receipt cannot be read as pinning bytes it no
# longer measures.
sub("| `fp-driver-d2.sh` (**the subject**) | `2bd12fc8ff333b6c7a49dc3b64c2dd1d3608d7a3f0a6f1b67e44e2ecedd5b1db` |\n"
    "| `fp-driver-d2.diff` (exact diff against r10) | `82a7b35ec67d13bd2ef2181ef168091182624ced09118ffb53909d84af63ab13` |\n",
    "| `fp-driver-d2.sh` (**the subject**, current) | `%s` |\n"
    "| `fp-driver-d2.diff` (exact diff against r10) | `82a7b35ec67d13bd2ef2181ef168091182624ced09118ffb53909d84af63ab13` |\n"
    "| `fp-driver-d2-81dc4fe8-to-f7b7773f.diff` (the timestamp repair, focused) | `%s` |\n"
    "| `history/fp-driver-d2-2bd12fc8.sh` (superseded; the subject of Sec. 5) | `2bd12fc8ff333b6c7a49dc3b64c2dd1d3608d7a3f0a6f1b67e44e2ecedd5b1db` |\n"
    "| `history/fp-driver-d2-81dc4fe8.sh` (superseded) | `81dc4fe8288105ed65998f2b152896f1cd4e068e29f1d3b1defe3ae5ed1c315d` |\n"
    % (sha('fp-driver-d2.sh'), sha('fp-driver-d2-81dc4fe8-to-f7b7773f.diff')),
    'Sec.1 subject + lineage rows')

sub("| `rig-d2/make-d2-stubs.sh` | `ebf8a7b567adfdf4eef328f5f006c48ab837f6f6a11c8b78fd120d6320349c56` |\n"
    "| `rig-d2/run-d2.sh` | `23ca22dfeb7c2dd619a0b8f64145a87c33553b4f91aacc983b8a8f3a6a252b4c` |\n",
    "| `rig-d2/make-d2-stubs.sh` (repaired, Sec. 5b) | `%s` |\n"
    "| `rig-d2/bin/pwsh` (the GENERATED stub both reruns used) | `%s` |\n"
    "| `rig-d2/run-d2.sh` (R7 arm corrected, Sec. 5b) | `%s` |\n"
    % (sha('rig-d2/make-d2-stubs.sh'), sha('rig-d2/bin/pwsh'), sha('rig-d2/run-d2.sh')),
    'Sec.1 rig rows')

sub("| `rig-d2/all-run.txt` (the control's own output) | `8008a2c2d38668e410ed803d88a71860052dc449d03d86c366da4576605f209a` |\n",
    "| `rig-d2/all-run.txt` (the full-suite output, driver `2bd12fc8`) | `8008a2c2d38668e410ed803d88a71860052dc449d03d86c366da4576605f209a` |\n"
    "| `rig-d2/residual-run.txt` (the focused run, Sec. 5a) | `%s` |\n"
    "| `rig-d2/r7-run.txt` (R7 corrected rerun) | `%s` |\n"
    "| `rig-d2/r9-rerun.txt` (R9 rerun on the repaired fixture) | `%s` |\n"
    "| `rig-d2/r10-rerun.txt` (R10 rerun on the repaired fixture) | `%s` |\n"
    % (sha('rig-d2/residual-run.txt'), sha('rig-d2/r7-run.txt'),
       sha('rig-d2/r9-rerun.txt'), sha('rig-d2/r10-rerun.txt')),
    'Sec.1 run-output rows')

io.open(P, 'w', encoding='utf-8', newline='\n').write(s)
print('WROTE ' + P)
