#!/usr/bin/env python3
"""content-length-diff-misses-same-length-edits   ·   run: python3 content-length-diff.py

A deploy verifier asks "is local the same as live?". One check reads
Content-Length. One hashes the body. The edit 4:36 -> 4:49 changes neither
the character count nor the byte count. It shipped three stale files.
"""
import hashlib, http.server, socketserver, threading, urllib.request

LIVE  = "<p>Episode Two - 4:36</p>".encode()   # what is published
LOCAL = "<p>Episode Two - 4:49</p>".encode()   # what was just edited

class H(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Length", str(len(LIVE)))
        self.end_headers(); self.wfile.write(LIVE)
    def log_message(self, *a): pass

srv = socketserver.TCPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
with urllib.request.urlopen("http://127.0.0.1:%d/" % srv.server_address[1]) as r:
    live_len, live_body = int(r.headers["Content-Length"]), r.read()
srv.shutdown()

ceremony = "IDENTICAL" if live_len == len(LOCAL) else "DIFFERS"
oracle   = "IDENTICAL" if hashlib.sha256(live_body).digest() == \
                          hashlib.sha256(LOCAL).digest() else "DIFFERS"

print("local %d bytes / live %d bytes" % (len(LOCAL), live_len))
print("  CEREMONY  Content-Length equal ->", ceremony,
      "  <-- WRONG, the files differ" if ceremony == "IDENTICAL" else "")
print("  ORACLE    sha256(body) equal   ->", oracle,
      "  <-- CORRECT, convicts" if oracle == "DIFFERS" else "")
print()
print("Byte count is invariant under the entire class of edits this check")
print("existed to catch. It had one reachable state, and it printed it.")
ok = ceremony == "IDENTICAL" and oracle == "DIFFERS"
print("\nRESULT:", "reproduced" if ok else "NOT reproduced")
raise SystemExit(0 if ok else 1)
