#!/usr/bin/python3
"""WSL proxy port switcher. Strict mode = sing-box TUN + persistent egress guard.
Only this WSL distribution is affected. Local/LAN and inbound response traffic are exempt.
HTTP CONNECT cannot carry arbitrary UDP; DNS is tunneled, other public UDP is rejected.
"""
import argparse
import datetime
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import socket
import subprocess
import sys
import tempfile
import time

VERSION = '1.0'
MARKER = '# Managed by wsl-proxy'
KEYS = ('HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy', 'ALL_PROXY', 'all_proxy', 'NO_PROXY', 'no_proxy')
BYPASS = 'localhost,127.0.0.1,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,.lan,.local'
LOCAL = ['127.0.0.0/8', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '169.254.0.0/16', '::1/128', 'fc00::/7', 'fe80::/10']
BINARY_SHA256 = '1264361b5f8868c8768f7555d3e77e20118bf503c41ac08bb290a0d99056aa3a'
SERVICE = 'wsl-proxy-tun.service'
ROOTDIR = Path('/etc/wsl-proxy')


def run(argv, **kwargs):
    return subprocess.run([str(x) for x in argv], check=True, text=True, **kwargs)


def proxy_env(port):
    url = f'http://127.0.0.1:{port}'
    return {k: BYPASS if k.lower() == 'no_proxy' else url for k in KEYS}


def env_text(port, shell=False):
    return '\n'.join(('export ' if shell else '') + k + '=' + shlex.quote(v) for k, v in proxy_env(port).items()) + '\n'


def tun_config(port):
    return {
        'log': {'level': 'warn', 'timestamp': True},
        'dns': {'servers': [{'type': 'https', 'tag': 'proxy-dns', 'server': '1.1.1.1', 'server_port': 443,
                            'path': '/dns-query', 'tls': {'enabled': True, 'server_name': 'cloudflare-dns.com'}, 'detour': 'selected-proxy'}],
                'final': 'proxy-dns'},
        'inbounds': [{'type': 'tun', 'tag': 'wsl-tun', 'interface_name': 'wslproxy0',
                      'address': ['172.31.255.1/30', 'fdfe:dcba:9876::1/126'], 'mtu': 1500,
                      'auto_route': True, 'auto_redirect': True, 'strict_route': True, 'stack': 'mixed',
                      'route_exclude_address': LOCAL}],
        'outbounds': [{'type': 'http', 'tag': 'selected-proxy', 'server': '127.0.0.1',
                       'server_port': port, 'bind_interface': 'lo'}],
        'route': {'rules': [{'port': 53, 'action': 'hijack-dns'},
                             {'network': 'udp', 'action': 'reject'}], 'final': 'selected-proxy'}
    }


NFT = '''table inet wsl_proxy_guard {
 chain output {
  type filter hook output priority 100; policy accept;
  oifname "lo" accept
  ip daddr { 10.0.0.0/8, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16 } accept
  ip6 daddr { ::1/128, fc00::/7, fe80::/10 } accept
  ct direction reply accept
  oifname "wslproxy0" accept
  reject with icmpx type admin-prohibited
 }
 chain forward {
  type filter hook forward priority 100; policy accept;
  ip daddr { 10.0.0.0/8, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16 } accept
  ip6 daddr { ::1/128, fc00::/7, fe80::/10 } accept
  ct direction reply accept
  oifname "wslproxy0" accept
  reject with icmpx type admin-prohibited
 }
}
'''


GUARD_HELPER = '''#!/usr/bin/python3
import pathlib, subprocess
existing = subprocess.run(['nft', 'list', 'table', 'inet', 'wsl_proxy_guard'], capture_output=True).returncode == 0
rules = pathlib.Path('/etc/wsl-proxy/guard.nft').read_text()
if existing: rules = 'delete table inet wsl_proxy_guard\\n' + rules
subprocess.run(['nft', '-f', '-'], input=rules, text=True, check=True)
'''


class Changes:
    def __init__(self, backup):
        self.backup = backup
        self.backup.mkdir(parents=True, mode=0o700)
        self.entries = []

    def write(self, path, text, mode=None):
        path = Path(path)
        if path.is_symlink():
            raise RuntimeError(f'Refusing to overwrite symlink: {path}')
        old = path.read_bytes() if path.exists() else None
        data = text.encode()
        if old == data:
            return
        index = str(len(self.entries))
        oldmode = path.stat().st_mode & 0o777 if old is not None else None
        if old is not None:
            b = self.backup / index
            b.write_bytes(old)
            b.chmod(0o600)
        self.entries.append({'path': str(path), 'backup': index if old is not None else None, 'mode': oldmode})
        (self.backup / 'manifest.json').write_text(json.dumps(self.entries, indent=2))
        path.parent.mkdir(parents=True, exist_ok=True)
        fd, tmp = tempfile.mkstemp(prefix='.wsl-proxy-', dir=path.parent)
        try:
            os.fchmod(fd, mode if mode is not None else oldmode if oldmode is not None else 0o600)
            with os.fdopen(fd, 'wb') as f:
                f.write(data)
                f.flush()
                os.fsync(f.fileno())
            os.replace(tmp, path)
        finally:
            if os.path.exists(tmp): os.unlink(tmp)

    def rollback(self):
        for e in reversed(self.entries):
            p = Path(e['path'])
            if e['backup'] is None:
                p.unlink(missing_ok=True)
            else:
                p.write_bytes((self.backup / e['backup']).read_bytes())
                p.chmod(e['mode'])


def replace_dotenv(text, port):
    values = proxy_env(port)
    seen = set()
    out = []
    for line in text.splitlines():
        match = re.match(r'^\s*(?:export\s+)?([A-Za-z_][A-Za-z_0-9]*)\s*=', line)
        if match and match[1] in values:
            key = match[1]
            if key not in seen:
                out.append(key + '=' + values[key])
            seen.add(key)
        else:
            out.append(line)
    out.extend(k + '=' + values[k] for k in KEYS if k not in seen)
    return '\n'.join(out) + '\n'


def update_shell(text, port):
    # Only standalone proxy assignments; preserve functions, unrelated settings and secrets.
    out = []
    inside = False
    for line in text.splitlines():
        if line == '# wsl-proxy environment BEGIN':
            inside = True
            continue
        if inside:
            if line == '# wsl-proxy environment END': inside = False
            continue
        if re.match(r'^\s*(?:export\s+)?(?:' + '|'.join(KEYS) + r')=', line):
            continue
        out.append(line)
    if inside:
        raise RuntimeError('Unterminated managed block in shell config; refusing to truncate it')
    out += ['# wsl-proxy environment BEGIN',
            '[ -r "$HOME/.config/wsl-proxy/env.sh" ] && . "$HOME/.config/wsl-proxy/env.sh"',
            '# wsl-proxy environment END']
    return '\n'.join(out) + '\n'


def home_plan(home, port):
    plan = {home / '.config/wsl-proxy/env.sh': MARKER + '\n' + env_text(port, True),
            home / '.config/environment.d/90-proxy.conf': MARKER + '\n' + env_text(port),
            home / '.k2p-wsl-proxy': MARKER + '\n' + env_text(port, True)}
    for filename in ['.bashrc', '.profile', '.zshrc', '.zprofile', '.bash_profile']:
        p = home / filename
        if p.exists(): plan[p] = update_shell(p.read_text(), port)
    homes = [home / '.hermes'] + sorted((home / '.hermes/profiles').glob('*'))
    for h in homes + [home / '.codex']:
        if h.is_dir():
            p = h / '.env'
            plan[p] = replace_dotenv(p.read_text() if p.exists() else '', port)
    unitsdir = home / '.config/systemd/user'
    if unitsdir.exists():
        # All installed user services: one consistent environment, without rewriting their other settings.
        units = set(p.name for p in unitsdir.glob('*.service'))
        for unit in units:
            p = unitsdir / (unit + '.d/zz-wsl-proxy.conf')
            plan[p] = MARKER + '\n[Service]\n' + ''.join(f'Environment="{k}={v}"\n' for k,v in proxy_env(port).items())
        # Replace only proxy Environment assignments in existing drop-ins; late z*.conf must not win.
        for p in unitsdir.glob('*.service.d/*.conf'):
            text = p.read_text()
            new = text
            for key,value in proxy_env(port).items():
                # Match one assignment, never consume additional Environment= fields on the same line.
                new = re.sub(r'(?m)^(\s*Environment=)(["\']?)' + re.escape(key) + r'=[^"\'\s\n]*(\2)',
                             lambda m: f'{m[1]}{m[2]}{key}={value}{m[3]}', new)
            if new != text: plan[p] = new
    # Explicit per-app proxy settings override environment variables too.
    for name in ['.npmrc', '.wgetrc']:
        p = home / name
        if p.exists():
            text = p.read_text()
            text = re.sub(r'(?mi)^(\s*(?:proxy|https-proxy|http_proxy|https_proxy)\s*=\s*).+$',
                          lambda m: m[1] + f'http://127.0.0.1:{port}', text)
            plan[p] = text
    for name in ['.gitconfig', '.ssh/config']:
        p = home / name
        if p.exists():
            # Change only existing literal loopback proxy ports on proxy-bearing lines.
            lines = []
            for line in p.read_text().splitlines():
                if ('proxy' in line.lower() or '127.0.0.1:' in line and 'ProxyCommand' in line):
                    line = re.sub(r'127\.0\.0\.1:(?:10809|12334|2080|7890|7897|18080)', f'127.0.0.1:{port}', line)
                lines.append(line)
            plan[p] = '\n'.join(lines) + '\n'
    return plan


def validate_port(s):
    if not re.fullmatch(r'[0-9]{1,5}', s) or not 1 <= int(s) <= 65535:
        raise argparse.ArgumentTypeError('Port must be an integer 1..65535')
    return int(s)


def preflight(port):
    with socket.create_connection(('127.0.0.1', port), timeout=3): pass
    result = run(['curl', '--silent', '--show-error', '--noproxy', '', '--proxy', f'http://127.0.0.1:{port}',
                  '--connect-timeout', '5', '--max-time', '15', '-o', '/dev/null', '-w', '%{http_code}',
                  'https://chatgpt.com/backend-api/me'], capture_output=True)
    code = result.stdout.strip()
    if code not in ('200','401','403','405'):
        raise RuntimeError('Proxy HTTPS check failed, HTTP ' + code)
    print(f'Proxy 127.0.0.1:{port}: HTTPS reachable (HTTP {code}, not an authenticated model test).')


def root_command(args):
    if os.geteuid() == 0: return [sys.executable, __file__, *args]
    if shutil.which('sudo') and subprocess.run(['sudo','-n','true'],capture_output=True).returncode == 0:
        return ['sudo', '-n', '/usr/bin/python3', str(Path(__file__).resolve()), *args]
    wsl = shutil.which('wsl.exe')
    if wsl:
        distro = os.environ.get('WSL_DISTRO_NAME') or 'Ubuntu-24.04'
        # Avoid writing the wrong distribution when called from a stripped systemd environment.
        probe = run([wsl,'-d',distro,'-u','root','--exec','/bin/cat','/etc/machine-id'],capture_output=True)
        if probe.stdout.strip() != Path('/etc/machine-id').read_text().strip():
            raise RuntimeError('WSL distribution identity mismatch; refusing elevation')
        return [wsl,'-d',distro,'-u','root','--exec','/usr/bin/python3',str(Path(__file__).resolve()),*args]
    raise RuntimeError('Root access required for TUN; run this command with sudo or use --env-only')


def root_apply(port, enable_tun):
    if os.geteuid() != 0: raise RuntimeError('Root required')
    ROOTDIR.mkdir(mode=0o755, exist_ok=True)
    binary = ROOTDIR / 'sing-box'
    source = Path(__file__).resolve().parent / 'sing-box'
    if hashlib.sha256(source.read_bytes()).hexdigest() != BINARY_SHA256:
        raise RuntimeError('Bundled sing-box checksum mismatch')
    if not binary.exists():
        shutil.copy2(source,binary); binary.chmod(0o755)
    elif hashlib.sha256(binary.read_bytes()).hexdigest() != BINARY_SHA256:
        raise RuntimeError('Installed sing-box checksum mismatch')
    conf = json.dumps(tun_config(port), indent=2) + '\n'
    checked = ROOTDIR / 'candidate.json'
    checked.write_text(conf)
    run([binary,'check','-c',checked])
    checked.unlink()
    if enable_tun:
        if not Path('/dev/net/tun').exists(): raise RuntimeError('/dev/net/tun unavailable')
        if not shutil.which('nft'): raise RuntimeError('nftables required; install nftables first')
        # Never override another VPN silently.
        existing = run(['ip','-j','link','show'], capture_output=True).stdout
        vpns = [x['ifname'] for x in json.loads(existing) if re.match(r'^(tailscale|wg\d|tun\d|utun)',x['ifname'])]
        if vpns: raise RuntimeError('Existing VPN interfaces: '+','.join(vpns)+'. Resolve routing conflict first; --env-only is available.')
    stamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f')
    changes = Changes(Path('/var/lib/wsl-proxy/backups') / stamp)
    was_active = subprocess.run(['systemctl','is-active','--quiet',SERVICE]).returncode == 0
    guard_before = subprocess.run(['nft','list','table','inet','wsl_proxy_guard'],capture_output=True,text=True) if shutil.which('nft') else None
    try:
        p = Path('/etc/environment')
        changes.write(p, replace_dotenv(p.read_text() if p.exists() else '',port), 0o644)
        changes.write(Path('/etc/profile.d/wsl-proxy.sh'),MARKER+'\n'+env_text(port,True),0o644)
        if enable_tun or was_active:
            changes.write(ROOTDIR/'config.json',conf,0o644)
        if enable_tun:
            changes.write(ROOTDIR/'guard.nft',NFT,0o644)
            changes.write(ROOTDIR/'guard.py',GUARD_HELPER,0o755)
            guard_unit = MARKER + '''
[Unit]
Description=WSL proxy fail-closed egress guard
Before=wsl-proxy-tun.service
[Service]
Type=oneshot
ExecStart=/usr/bin/python3 /etc/wsl-proxy/guard.py
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
'''
            guardpath=Path('/etc/systemd/system/wsl-proxy-guard.service')
            if guardpath.exists() and MARKER not in guardpath.read_text(): raise RuntimeError('Unmanaged guard unit name collision')
            changes.write(guardpath,guard_unit,0o644)
            unit = MARKER + '''
[Unit]
Description=WSL forced TCP proxy (sing-box TUN)
After=network-online.target wsl-proxy-guard.service
Requires=wsl-proxy-guard.service
Wants=network-online.target
[Service]
Type=simple
ExecStart=/etc/wsl-proxy/sing-box run -c /etc/wsl-proxy/config.json
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
'''
            unitpath=Path('/etc/systemd/system')/SERVICE
            if unitpath.exists() and MARKER not in unitpath.read_text(): raise RuntimeError('Unmanaged unit name collision')
            changes.write(unitpath,unit,0o644)
            run(['systemctl','daemon-reload'])
            run(['systemctl','enable','wsl-proxy-guard.service',SERVICE])
            run(['systemctl','start','wsl-proxy-guard.service'])
            run(['systemctl','restart',SERVICE])
            for _ in range(30):
                if Path('/sys/class/net/wslproxy0').exists(): break
                time.sleep(.2)
            else: raise RuntimeError('TUN did not start; inspect journalctl -u '+SERVICE)
            # Atomic nft transaction: replace only our own table, never flush host/Docker rules.
            exists_now = subprocess.run(['nft','list','table','inet','wsl_proxy_guard'],capture_output=True).returncode == 0
            nft = ('delete table inet wsl_proxy_guard\n' if exists_now else '')+NFT
            run(['nft','-f','-'],input=nft)
            # No proxy environment and no explicit curl proxy: this exercises transparent routing.
            run(['curl','--noproxy','*','--silent','--show-error','--connect-timeout','6','--max-time','20',
                 '-o','/dev/null','--write-out','Transparent TCP: HTTP %{http_code}\n','https://1.1.1.1/cdn-cgi/trace'])
            print('TUN active. Public TCP forced through selected HTTP CONNECT proxy. Public non-DNS UDP rejected.')
            print('Local/LAN and replies to inbound connections exempt; WSL host DNS and other distributions are not covered.')
        elif was_active:
            run(['systemctl','restart',SERVICE])
        print('Root backup:',changes.backup)
    except Exception:
        if not was_active:
            subprocess.run(['systemctl','disable','--now',SERVICE,'wsl-proxy-guard.service'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
        changes.rollback()
        run(['systemctl','daemon-reload'])
        if was_active: subprocess.run(['systemctl','restart',SERVICE])
        if shutil.which('nft'):
            subprocess.run(['nft','delete','table','inet','wsl_proxy_guard'],capture_output=True)
            if guard_before and guard_before.returncode==0:
                subprocess.run(['nft','-f','-'],input=guard_before.stdout,text=True)
        raise


def root_off():
    if os.geteuid() != 0: raise RuntimeError('Root required')
    run(['systemctl','disable','--now',SERVICE])
    subprocess.run(['systemctl','disable','--now','wsl-proxy-guard.service'],check=False)
    if shutil.which('nft'): subprocess.run(['nft','delete','table','inet','wsl_proxy_guard'],capture_output=True)
    print('TUN and its egress guard removed. App proxy environment settings are retained.')


def main():
    ap=argparse.ArgumentParser(description=__doc__)
    ap.add_argument('port',nargs='?',type=validate_port)
    modes=ap.add_mutually_exclusive_group()
    modes.add_argument('--env-only',action='store_true',help='Only unify configuration (default); not forced global traffic')
    modes.add_argument('--strict',action='store_true',help='Force public TCP with TUN and fail-closed guard; refuses competing VPNs')
    ap.add_argument('--dry-run',action='store_true',help='Preview paths, do not write or change routing')
    ap.add_argument('--status',action='store_true')
    ap.add_argument('--tun-off',action='store_true',help='Remove TUN and guard, retain app proxy configuration')
    ap.add_argument('--restart',action='store_true',help='Restart user Hermes gateways and Codex daemon; run from an outside terminal')
    ap.add_argument('--exports',action='store_true',help='Print shell exports for current selected port')
    ap.add_argument('--root-action',choices=['apply','env','off'],help=argparse.SUPPRESS)
    args=ap.parse_args()
    args.env_only = not args.strict
    if args.root_action:
        if args.root_action=='off': root_off()
        else:
            if not args.port: ap.error('port required')
            root_apply(args.port,args.root_action=='apply')
        return
    home=Path.home()
    if args.tun_off:
        run(root_command(['--root-action','off'])); return
    state=home/'.config/wsl-proxy/state.json'
    if args.status:
        print(state.read_text() if state.exists() else 'No port selected by this script yet.')
        subprocess.run(['systemctl','is-active',SERVICE]); return
    if args.exports:
        if not state.exists(): raise RuntimeError('No selected port')
        print(env_text(json.loads(state.read_text())['port'],True),end=''); return
    if args.port is None:
        args.port=validate_port(input('Proxy port (10809 / 12334 / 2080): ').strip())
    if args.port in (53,22): raise RuntimeError('Refusing common DNS/SSH service port')
    plan=home_plan(home,args.port)
    if args.dry_run:
        print('Mode:', 'environment only' if args.env_only else 'forced public TCP (TUN + nft guard)')
        print('Target:',f'127.0.0.1:{args.port}')
        print('\n'.join(str(p) for p in sorted(plan)))
        print('Root changes: /etc/environment, /etc/profile.d/wsl-proxy.sh; TUN config/service/guard in strict mode.')
        return
    preflight(args.port)
    rootargs=['--root-action','env' if args.env_only else 'apply',str(args.port)]
    rootcmd=root_command(rootargs)
    basedir=home/'.local/state/wsl-proxy'
    basedir.mkdir(parents=True,exist_ok=True)
    with (basedir/'lock').open('w') as lock:
        fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
        changes=Changes(basedir/'backups'/datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f'))
        try:
            for p,text in plan.items(): changes.write(p,text)
            run(rootcmd)
            changes.write(state,json.dumps({'port':args.port,'mode':'env-only' if args.env_only else 'tun',
                                            'updated':datetime.datetime.now().isoformat()},indent=2)+'\n')
            run(['systemctl','--user','daemon-reload'])
            run(['systemctl','--user','set-environment',*[f'{k}={v}' for k,v in proxy_env(args.port).items()]])
        except Exception:
            changes.rollback()
            raise
    print('User backup:',changes.backup)
    print('Selected port:',args.port)
    print('Existing process environments do not change automatically. Reopen terminals/apps; or use --restart for known daemons.')
    print('Current shell: eval "$(wsl-proxy --exports)"')
    if args.restart:
        units=run(['systemctl','--user','list-units','--type=service','--no-legend','--plain'],capture_output=True).stdout
        for line in units.splitlines():
            unit=line.split()[0]
            if unit.startswith('hermes-gateway') and unit.endswith('.service'):
                run(['systemctl','--user','restart',unit])
        codex=home/'.codex/packages/standalone/current/bin/codex'
        if codex.exists(): run([codex,'app-server','daemon','restart'],env={**os.environ,**proxy_env(args.port)})


if __name__=='__main__':
    try: main()
    except (Exception,KeyboardInterrupt) as exc:
        print(f'wsl-proxy: {exc}',file=sys.stderr)
        sys.exit(1)
