#!/usr/bin/env python3
"""Start a detached HTTP file server for the IPA file, accessible via Tailscale."""
import subprocess, sys, os

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

IPA_DIR = r'E:\ios'
IPA_NAME = 'GSMDriver-3.19.0-patched54-unsigned.ipa'

CREATE_BREAKAWAY = 0x01000000

# serve on port 8080, sharing the directory that has the IPA
code = (
    "import http.server, os\n"
    "os.chdir(r'%s')\n"
    "httpd = http.server.HTTPServer(('0.0.0.0', 8080), http.server.SimpleHTTPRequestHandler)\n"
    "print('serving on 0.0.0.0:8080')\n"
    "httpd.serve_forever()\n"
) % IPA_DIR

code_file = os.path.join(IPA_DIR, '_serve.py')
open(code_file, 'w').write(code)

try:
    p = subprocess.Popen(
        [sys.executable, code_file],
        creationflags=CREATE_BREAKAWAY,
        stdout=open(os.path.join(IPA_DIR, '_serve.log'), 'w'),
        stderr=subprocess.STDOUT)
    print('HTTP server started detached, pid', p.pid)
except PermissionError:
    # breakaway not allowed, start normally
    p = subprocess.Popen(
        [sys.executable, code_file],
        stdout=open(os.path.join(IPA_DIR, '_serve.log'), 'w'),
        stderr=subprocess.STDOUT)
    print('HTTP server started (no breakaway), pid', p.pid)

print('IPA: %s' % os.path.join(IPA_DIR, IPA_NAME))
print('URL: http://100.118.103.32:8080/%s' % IPA_NAME)
