import os,sys,pathlib,subprocess,datetime,re,json
root=pathlib.Path(__file__).resolve().parent
if len(sys.argv)>1 and sys.argv[1]=='inside':
    tree,checkout,uid,gid,user,node=sys.argv[2:]
    subprocess.run(['mount','--make-rprivate','/'],check=True)
    subprocess.run(['mount','--bind',tree,'/sys/fs/cgroup'],check=True)
    subprocess.run(['mount','-o','remount,bind,ro','/sys/fs/cgroup'],check=True)
    # Hide live T3 state; the installed service is queried read-only over its existing bus.
    subprocess.run(['mount','--bind',tree+'/../t3-home',os.path.expanduser('~'+user)+'/.t3'],check=True)
    home=os.path.expanduser('~'+user)
    fixture=pathlib.Path(tree).parent
    user_systemd=fixture/'user-systemd'
    (user_systemd/'user').mkdir(parents=True)
    (user_systemd/'user'/'t3code.service').write_bytes(pathlib.Path(home+'/.config/systemd/user/t3code.service').read_bytes())
    for entry in [user_systemd,user_systemd/'user',user_systemd/'user'/'t3code.service']:
        os.chown(entry,int(uid),int(gid))
    system_systemd=fixture/'system-systemd';system_systemd.mkdir()
    subprocess.run(['mount','--bind',str(user_systemd),home+'/.config/systemd'],check=True)
    subprocess.run(['mount','--bind',str(system_systemd),'/etc/systemd/system'],check=True)
    manager_pid=subprocess.check_output(['systemctl','show','--property=MainPID','--value','user@'+uid+'.service'],text=True).strip()
    score=fixture/'manager-oom-score';score.write_text('200\n')
    subprocess.run(['mount','--bind',str(score),'/proc/'+manager_pid+'/oom_score_adj'],check=True)
    os.setgroups([]);os.setgid(int(gid));os.setuid(int(uid))
    os.environ['HOME']=os.path.expanduser('~'+user)
    os.environ['USER']=user
    os.environ['XDG_RUNTIME_DIR']='/run/user/'+uid
    os.environ['DBUS_SESSION_BUS_ADDRESS']='unix:path=/run/user/'+uid+'/bus'
    os.chdir(checkout)
    print('Linux / systemd; private mount namespace; memory controller disabled fixture',flush=True)
    print('$ cat /sys/fs/cgroup/cgroup.controllers',flush=True)
    print(pathlib.Path('/sys/fs/cgroup/cgroup.controllers').read_text().strip(),flush=True)
    print('No memory.low or memory.min files exist in this fixture.',flush=True)
    print('Drop-in writes and manager OOM-score writes are confined to private mounts.',flush=True)
    print('systemctl queries and daemon-reload use the real managers; no service is restarted.\n',flush=True)
    env=os.environ.copy();env['NO_COLOR']='1';env['TERM']='dumb'
    print("$ t3 service status --base-dir '%h/.t3'",flush=True)
    p=subprocess.run([node,'apps/server/src/bin.ts','service','status','--base-dir','%h/.t3'],env=env)
    print('Exit:',p.returncode,flush=True)
    print('\n$ t3 service protect --base-dir \'%h/.t3\'   # decline remote protection; accept application in isolated mounts',flush=True)
    # Prompt requires a terminal; drive the actual CLI through a PTY.
    import pty,select,time
    pid,fd=pty.fork()
    if pid==0: os.execve(node,[node,'apps/server/src/bin.ts','service','protect','--base-dir','%h/.t3'],env)
    buf=b'';answered=0
    while True:
        try: data=os.read(fd,65536)
        except OSError: break
        if not data:break
        os.write(1,data);buf+=data
        count=buf.count(b'(y/N)')+buf.count(b'(Y/n)')
        if count>answered:
            os.write(fd,b'n\r' if answered==0 else b'y\r');answered=count
        # Effect prompt uses its own rendered suffix.
        if b'Also protect' in buf and answered==0:
            os.write(fd,b'n\r');answered=1
        if b'Apply these settings?' in buf and answered<2:
            os.write(fd,b'y\r');answered=2
    _,status=os.waitpid(pid,0);print('\nExit:',os.waitstatus_to_exitcode(status),flush=True)
    print("\n$ t3 service status --base-dir '%h/.t3'   # after protect",flush=True)
    p=subprocess.run([node,'apps/server/src/bin.ts','service','status','--base-dir','%h/.t3'],env=env)
    print('Exit:',p.returncode,flush=True)
    print('\nIsolated application check: system drop-in exists:',(system_systemd/'user.slice.d'/'90-t3code-protect.conf').exists(),flush=True)
    print('Isolated manager OOM-score write:',score.read_text().strip(),flush=True)
    sys.exit(0)
run=root/('run-'+datetime.datetime.now(datetime.UTC).strftime('%Y%m%dT%H%M%SZ'));run.mkdir()
(run/'cgroup').mkdir();(run/'t3-home').mkdir()
(run/'cgroup'/'cgroup.controllers').write_text('cpuset cpu io pids\n')
subprocess.run(['chmod','777',str(run/'t3-home')],check=True)
node=subprocess.check_output(['node','-p','process.execPath'],text=True).strip()
for side,checkout in zip(['before','after'],sys.argv[1:3]):
    checkout=str(pathlib.Path(checkout).resolve())
    side_dir=run/side;side_dir.mkdir()
    (side_dir/'cgroup').mkdir();(side_dir/'t3-home').mkdir()
    (side_dir/'cgroup'/'cgroup.controllers').write_text('cpuset cpu io pids\n')
    os.chmod(side_dir/'t3-home',0o777)
    result=subprocess.run(['sudo','-n','unshare','-m',sys.executable,str(pathlib.Path(__file__).resolve()),'inside',str(side_dir/'cgroup'),checkout,str(os.getuid()),str(os.getgid()),os.environ['USER'],node],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=120)
    text=result.stdout.decode(errors='replace')
    text=re.sub(r'\x1b\][^\x07]*\x07','',text);text=re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]','',text)
    text=text.replace(checkout,'<checkout>').replace(os.path.expanduser('~'),'$HOME')
    text=re.sub(r'(?m)^  Logs:.*$', '  Logs: <isolated log path>',text)
    (run/(side+'.txt')).write_text(text)
    print(side,result.returncode,text)
print('OUTPUT',run)
