import os, sys, subprocess as sp, time, pathlib, signal, hashlib, json
root=pathlib.Path(__file__).resolve().parent
side, sha, old, new=sys.argv[1:]
run=root/(side+'-'+time.strftime('%Y%m%d-%H%M%S')); run.mkdir()
log=run/'transcript.txt'
def say(s):
    with log.open('a') as f: f.write(s+'\n')
    print(s,flush=True)
def command(args):
    p=sp.run(args,stdout=sp.PIPE,stderr=sp.STDOUT,text=True)
    return p.returncode,p.stdout
processes=[]
def start(args,**kw):
    p=sp.Popen(args,**kw); processes.append(p); return p
def stop(p):
    if p.poll() is None:
        p.terminate()
        try:p.wait(timeout=15)
        except sp.TimeoutExpired:p.kill();p.wait()
def status():
    for args in [ ['dpkg-query','-W','-f=${Status}\nVersion: ${Version}\nConfig-Version: ${Config-Version}\n','t3code'],['readlink','-f','/usr/bin/t3code'] ]:
        rc,out=command(args);say(out.strip() or '(launcher absent)')
    say('AppArmor file: '+str(pathlib.Path('/etc/apparmor.d/t3code').exists()))
    rc,out=command(['sudo','-n','cat','/sys/kernel/security/apparmor/profiles'])
    say('Kernel profile: '+next((x for x in out.splitlines() if x.startswith('t3code ')),'ABSENT'))
    rc,out=command(['update-alternatives','--query','t3code'])
    say(next((x for x in out.splitlines() if x.startswith('Value:')),out.strip()))
def stable(name):
    last=None
    for i in range(30):
        path=run/(name+f'-check-{i}.png')
        sp.run(['import','-window','root',str(path)],check=True)
        digest=hashlib.sha256(path.read_bytes()).hexdigest()
        if digest==last:
            final=run/(name+'.png');final.write_bytes(path.read_bytes());return str(final)
        last=digest;time.sleep(.5)
    raise RuntimeError('capture did not settle')
def launch(tag):
    env=os.environ.copy();env.update(T3CODE_HOME=str(run/'home'),T3CODE_DEV_SEED='0',T3CODE_ENVIRONMENT_LABEL='Ubuntu upgrade evidence',T3CODE_DISABLE_AUTO_UPDATE='1',XDG_CONFIG_HOME=str(run/'config'))
    p=start(['/opt/T3 Code (Nightly)/t3code','--disable-gpu'],env=env,stdout=(run/(tag+'-app.log')).open('w'),stderr=sp.STDOUT)
    for _ in range(120):
        rc,out=command(['wmctrl','-l'])
        matches=[x for x in out.splitlines() if 'T3 Code (Nightly)' in x]
        if matches:
            window=matches[0].split()[0]
            sp.run(['wmctrl','-ir',window,'-e','0,635,40,1260,980'])
            time.sleep(4)
            say('Launch: window T3 Code (Nightly) opened')
            rc,label=command(['cat',f'/proc/{p.pid}/attr/current']);say('Process AppArmor: '+label.strip())
            return p
        if p.poll() is not None:
            say('Launch: exited '+str(p.returncode)+'; NO WINDOW')
            raw=(run/(tag+'-app.log')).read_text(errors='replace')
            for line in raw.splitlines():
                if 'FATAL:' in line:say(line[line.index('FATAL:'):])
            return p
        time.sleep(.5)
    raise RuntimeError('app window not ready')
try:
    wm=start(['openbox'],stdout=sp.DEVNULL,stderr=sp.DEVNULL)
    say(('BEFORE' if side=='base' else 'AFTER')+' | interrupted Debian upgrade')
    say('Commit: '+sha)
    say('Ubuntu 24.04 | X11 1920x1080 | sandbox enabled')
    say('kernel.apparmor_restrict_unprivileged_userns = 1')
    term=start(['xterm','-title','Package upgrade evidence','-geometry','76x56+0+0','-fa','DejaVu Sans Mono','-fs','10','-bg','#101820','-fg','#f0f0f0','-xrm','XTerm*cursorBlink: false','-e','tail','-n','100','-f',str(log)],stdout=sp.DEVNULL,stderr=sp.DEVNULL)
    time.sleep(1)
    video=start(['ffmpeg','-y','-loglevel','error','-f','x11grab','-video_size','1920x1080','-framerate','10','-i',os.environ['DISPLAY'],'-c:v','libx264','-preset','ultrafast','-crf','24','-pix_fmt','yuv420p',str(run/'upgrade.mp4')],stdout=sp.DEVNULL,stderr=(run/'ffmpeg.log').open('w'))
    say('\n1. Install initial package and launch desktop Exec')
    rc,out=command(['sudo','-n','apt-get','install','-y',old]);(run/'install.log').write_text(out)
    if rc:raise RuntimeError('install failed: '+out)
    status();p=launch('initial');stable('initial-launch');stop(p);time.sleep(2)
    say('\n2. Interrupt upgrade after unpack, before postinst')
    say('$ sudo dpkg --unpack '+pathlib.Path(new).name)
    rc,out=command(['sudo','-n','dpkg','--unpack',new]);(run/'unpack.log').write_text(out)
    if rc:raise RuntimeError('unpack failed: '+out)
    status()
    say('\n3. Launch the same desktop Exec again')
    say('$ "/opt/T3 Code (Nightly)/t3code" --disable-gpu')
    p=launch('interrupted');time.sleep(2);capture=stable('interrupted-upgrade');time.sleep(3)
    stop(p);video.send_signal(signal.SIGINT);video.wait(timeout=20)
    (run/'summary.json').write_text(json.dumps({'side':side,'sha':sha,'capture':capture,'video':str(run/'upgrade.mp4')},indent=2))
finally:
    for p in reversed(processes):stop(p)
print('RUN_DIRECTORY='+str(run))
