#!/usr/bin/env python3
"""Start the usbmux->frida port forward DETACHED from the OpenCode job object so
it survives server restarts, then verify it is listening."""
import subprocess, sys, time, os

sys.stdout.reconfigure(encoding='utf-8')
UDID = '2f04999241eb80cae2d8a6176504af07002b86bd'
PY = sys.executable

CREATE_BREAKAWAY = 0x01000000

p = subprocess.Popen(
    [PY, '-m', 'pymobiledevice3', 'usbmux', 'forward', '7777', '7777', '--udid', UDID],
    creationflags=CREATE_BREAKAWAY,
    stdout=open(r'E:\ios\work319\fwd.log', 'wb'),
    stderr=subprocess.STDOUT)
print('forward started detached pid', p.pid)

time.sleep(4)
import socket
s = socket.socket()
s.settimeout(3)
try:
    s.connect(('127.0.0.1', 7777))
    print('port 7777 ACCEPTS connections')
except Exception as e:
    print('port 7777 not accepting:', e)
s.close()
