#!/usr/bin/python3
"""Keep the school SOCKS bridge connected; started silently by Clash Verge."""

import fcntl
import ipaddress
import json
import os
from pathlib import Path
import shlex
import signal
import socket
import subprocess
import sys
import time

ROOT = Path(__file__).resolve().parent
SETTINGS = json.loads((ROOT / "settings.json").read_text())
STATE = ROOT / "state"
PID_FILE = STATE / "openconnect.pid"
CONNECTION_LOG = STATE / "connection.log"
BINARY = Path(SETTINGS["openconnect"])
OCPROXY = Path(SETTINGS["ocproxy"])
ACCOUNT = SETTINGS["account"]
SERVICE = "cuhksz-vpn-cli"
BRIDGE_BINARIES = {str(OCPROXY), str(OCPROXY.resolve())}



def log(message):
    print(time.strftime("%Y-%m-%d %H:%M:%S"), message, flush=True)


def process_path(pid):
    result = subprocess.run(
        ["/bin/ps", "-p", str(pid), "-o", "comm="],
        capture_output=True, text=True, timeout=5,
    )
    return result.stdout.strip() if result.returncode == 0 else ""


def connected_pid():
    try:
        pid = int(PID_FILE.read_text().strip())
        if pid <= 1:
            return None
        os.kill(pid, 0)
        return pid if process_path(pid) in {str(BINARY), str(BINARY.resolve())} else None
    except (OSError, ValueError, subprocess.SubprocessError):
        return None


def cleanup_bridge():
    result = subprocess.run(
        ["/usr/sbin/lsof", "-t", "-nP", "-iTCP@127.0.0.1:11080", "-sTCP:LISTEN"],
        capture_output=True, text=True, timeout=10,
    )
    for value in set(result.stdout.split()):
        pid = int(value)
        if process_path(pid) not in BRIDGE_BINARIES:
            raise RuntimeError("Another application is using local port 11080.")
        try:
            os.kill(pid, signal.SIGTERM)
        except ProcessLookupError:
            pass


def gateway_address():
    # Never hand OpenConnect a Clash fake-IP: it caches that address on reconnect.
    try:
        for item in socket.getaddrinfo("vpn.cuhk.edu.cn", 443, socket.AF_INET):
            address = item[4][0]
            if ipaddress.ip_address(address).is_global:
                return address
    except socket.gaierror:
        pass
    response = subprocess.run(
        ["/usr/bin/curl", "--fail", "--silent", "--show-error", "--connect-timeout", "5",
         "--max-time", "10", "https://dns.alidns.com/resolve?name=vpn.cuhk.edu.cn&type=A"],
        capture_output=True, timeout=15, check=True,
    )
    for answer in json.loads(response.stdout).get("Answer", []):
        if answer.get("type") == 1 and ipaddress.ip_address(answer["data"]).is_global:
            return answer["data"]
    raise RuntimeError("The school VPN gateway did not resolve to a public address.")


def connect_once():
    gateway = gateway_address()
    # Credentials stay in Keychain and in process memory; never in files or argv.
    try:
        credential = subprocess.run(
            ["/usr/bin/security", "find-generic-password", "-s", SERVICE,
             "-a", ACCOUNT, "-w"],
            stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=120,
        )
    except subprocess.TimeoutExpired:
        log("macOS Keychain is waiting for authorization; retrying in 60 seconds.")
        return False
    if credential.returncode != 0 or not credential.stdout:
        raise RuntimeError("School password is unavailable in macOS Keychain.")
    cleanup_bridge()
    arguments = [
        str(BINARY), "--protocol=anyconnect", "--user=" + ACCOUNT, "--authgroup=CUHK(SZ)",
        "--passwd-on-stdin", "--non-inter", "--no-proxy", "--disable-ipv6",
        "--resolve=vpn.cuhk.edu.cn:" + gateway, "--reconnect-timeout=60",
        "--script-tun", "--script=" + shlex.quote(str(ROOT / "bridge.sh")),
        "--background", "--pid-file=" + str(PID_FILE),
        "https://vpn.cuhk.edu.cn/",
    ]
    with CONNECTION_LOG.open("wb") as output:
        process = subprocess.Popen(arguments, stdin=subprocess.PIPE,
                                   stdout=output, stderr=subprocess.STDOUT)
        try:
            process.communicate(input=credential.stdout.rstrip(b"\r\n") + b"\n", timeout=90)
        except subprocess.TimeoutExpired:
            process.send_signal(signal.SIGINT)
            try:
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                process.kill()
                process.wait()
            return False
    credential = None
    if process.returncode == 0:
        log("School VPN connected.")
        return True
    details = CONNECTION_LOG.read_text(errors="replace").lower()
    network_failures = (
        "failed to connect", "failed to open https", "getaddrinfo", "could not resolve",
        "connection timed out", "network is unreachable", "no route to host",
        "failed to reconnect", "connection refused", "connection reset",
    )
    if any(text in details for text in ("login failed", "authentication failed", "invalid password")):
        raise RuntimeError("School VPN authentication failed; automatic attempts stopped.")
    if any(text in details for text in network_failures):
        log("VPN gateway unavailable; retrying in 60 seconds.")
        return False
    raise RuntimeError("School VPN connection failed; check state/connection.log. Automatic attempts stopped.")


def control(action):
    if action == "status":
        if not connected_pid():
            print("OpenConnect is not running.")
            return 1
        check = subprocess.run(
            ["/usr/bin/curl", "--socks5-hostname", "127.0.0.1:11080",
             "--connect-timeout", "3", "--max-time", "8", "--silent", "--show-error",
             "--output", "/dev/null", "--write-out", "%{http_code}",
             "https://sis.cuhk.edu.cn/"], capture_output=True, text=True, timeout=10)
        ok = check.returncode == 0 and check.stdout.startswith(("2", "3"))
        print("VPN is connected; SIS is reachable." if ok else
              "OpenConnect is running, but SIS is not reachable; check the logs.")
        return 0 if ok else 1
    if action != "stop":
        raise RuntimeError("Supported commands: status, stop, run.")
    try:
        worker = int((STATE / "background.lock").read_text().strip())
        command = subprocess.run(["/bin/ps", "-p", str(worker), "-o", "args="],
                                 capture_output=True, text=True, timeout=5).stdout
        if worker > 1 and worker != os.getpid() and str(Path(__file__).resolve()) in command:
            os.kill(worker, signal.SIGTERM)
    except (OSError, ValueError):
        pass
    pid = connected_pid()
    if pid:
        os.kill(pid, signal.SIGINT)
        deadline = time.monotonic() + 5
        while connected_pid() and time.monotonic() < deadline:
            time.sleep(0.1)
    if not connected_pid():
        cleanup_bridge()
    print("School VPN helper stopped.")
    return 0


def main():
    os.umask(0o077)
    STATE.mkdir(mode=0o700, exist_ok=True)
    # An OS lock is released automatically after crashes and prevents duplicate workers.
    with (STATE / "background.lock").open("a+") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return 0
        lock.seek(0)
        lock.truncate()
        lock.write(str(os.getpid()) + "\n")
        lock.flush()
        log("Clash school VPN helper started.")
        while True:
            if connected_pid():
                time.sleep(15)
                continue
            try:
                succeeded = connect_once()
            except (subprocess.SubprocessError, socket.gaierror, json.JSONDecodeError) as error:
                log("Network or Keychain is temporarily unavailable; retrying in 60 seconds.")
                succeeded = False
            if not succeeded:
                time.sleep(60)
            else:
                time.sleep(15)


if __name__ == "__main__":
    try:
        action = sys.argv[1] if len(sys.argv) > 1 else "run"
        sys.exit(main() if action == "run" else control(action))
    except (RuntimeError, subprocess.SubprocessError, OSError) as error:
        log(str(error))
        sys.exit(1)
