#!/usr/bin/env python3
"""Continuously PIN OriginMgr.m_isLoggedIn = 1 (and clear loginError) from the
earliest moment OriginMgr exists, for the whole FIFA17 session.

Rationale (2026-07-31 live finding): setting the flag AFTER boot does nothing --
FIFA decides logged-out during its boot Blaze handshake (sends Authentication::
logout 1/0x46, never login 1/0x0A) and never re-auths. This pins the flag to 1
FROM BOOT so it is already set when FIFA does that handshake. Run BEFORE launching
FIFA; it auto-attaches to each FIFA17.exe and re-pins fast enough to win the race.

Needs ptrace_scope=0 (already set by root_arm.sh). Idempotent, harmless.
"""
import glob, os, struct, time

ORIGINMGR_PP = 0x1448acf50   # *(void**)0x1448acf50 -> OriginMgr
OFF_LOGGEDIN = 0x13          # OriginMgr.m_isLoggedIn (u8)
OFF_LOGINERR = 0x14          # OriginMgr.loginError (u32)

def find_pid():
    for d in glob.glob('/proc/[0-9]*'):
        try:
            if open(d + '/comm').read().strip() == 'FIFA17.exe':
                return int(os.path.basename(d))
        except Exception:
            pass
    return None

def main():
    print("[pin] waiting for FIFA17.exe (pin m_isLoggedIn=1 from boot)...", flush=True)
    last_pid = None
    first_pin = False
    while True:
        pid = find_pid()
        if not pid:
            last_pid = None; first_pin = False; time.sleep(0.2); continue
        if pid != last_pid:
            print(f"[pin] FIFA17.exe pid={pid}", flush=True); last_pid = pid; first_pin = False
        try:
            with open(f"/proc/{pid}/mem", "r+b") as f:
                f.seek(ORIGINMGR_PP); om = struct.unpack('<Q', f.read(8))[0]
                if om:
                    f.seek(om + OFF_LOGGEDIN); cur = f.read(1)
                    if cur != b'\x01':
                        f.seek(om + OFF_LOGGEDIN); f.write(b'\x01')
                        f.seek(om + OFF_LOGINERR); f.write(b'\x00\x00\x00\x00')
                        if not first_pin:
                            print(f"[pin] OriginMgr={om:#x} -> m_isLoggedIn PINNED=1 "
                                  f"(was {cur[0] if cur else '?'})", flush=True)
                            first_pin = True
        except Exception:
            pass
        time.sleep(0.02)   # 50 Hz: fast enough to win the boot race + hold it

if __name__ == "__main__":
    main()
