#!/usr/bin/env python3
"""Stream the unified log on the X, launch the app, and keep only the lines that
explain why the launch fails (AMFI / dyld / SpringBoard / runningboard)."""
import subprocess, sys, threading, time, os

sys.stdout.reconfigure(encoding='utf-8')

OUT = r'E:\ios\work319\syslog46.log'
UDID = '2f04999241eb80cae2d8a6176504af07002b86bd'

proc = subprocess.Popen(
    [sys.executable, '-m', 'pymobiledevice3', 'syslog', 'live', '--udid', UDID],
    stdout=open(OUT, 'wb'), stderr=subprocess.STDOUT)

time.sleep(6)

# launch via the root shell on device
subprocess.run([r'E:\ios\work319\fv17\Scripts\python.exe', r'E:\ios\work319\runsh.py',
                r'E:\ios\work319\launch46b.sh', '/var/mobile/Media/l46e.txt', '180'],
               capture_output=True, timeout=180)

time.sleep(10)
proc.terminate()
time.sleep(1)

keys = (b'AMFI', b'dyld', b'Driver', b'vn.gsm.md', b'runningboard', b'RunningBoard',
        b'SpringBoard', b'XPC', b'MIS', b'entitlement', b'Signature', b'codesign')
seen = 0
for line in open(OUT, 'rb').read().splitlines():
    if any(k in line for k in keys):
        try:
            t = line.decode('utf-8', 'replace')
        except Exception:
            continue
        if any(x in t for x in ('kernel', 'AMFI', 'dyld', 'runningd', 'RunningBoard', 'SpringBoard')):
            print(t[:400])
            seen += 1
        if seen > 60:
            break
print('--- total matching lines:', seen)
