#!/usr/bin/env python3
"""
zapret-discord-youtube для Ubuntu: подбор стратегии, запуск, автозапуск.

Стратегии берутся из релиза Flowseal/zapret-discord-youtube (general*.bat), вместо winws.exe работает nfqws
из bol-van/zapret, вместо WinDivert пакеты отдаёт nftables.

    sudo python3 zapret.py            меню
    sudo python3 zapret.py test       подобрать стратегию
    sudo python3 zapret.py run NAME   запустить до Ctrl+C
    sudo python3 zapret.py enable NAME / disable / update

Для окна (zapret-gui.py): install, start NAME, stop, autostart on|off, test --batch.
"""
import json
import os
import platform
import re
import shlex
import shutil
import signal
import subprocess
import sys
import tarfile
import tempfile
import threading
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime

API = 2   # версия команд для окна, zapret-gui.py её проверяет
ROOT = "/opt/zapret-discord-youtube"
BIN = ROOT + "/bin/"
LISTS = ROOT + "/lists/"
NFQWS = BIN + "nfqws"
SELF = ROOT + "/zapret.py"
SERVICE = "zapret-discord-youtube"
POLICY = "/usr/share/polkit-1/actions/pro.emptyprojects.zapret.policy"
UNIT = f"/etc/systemd/system/{SERVICE}.service"
TABLE = "zapret_dy"
QNUM = 200
MARK = "0x40000000"   # nfqws метит свои пакеты, их в очередь не отдаём
GAME_OFF = "12"       # так service.bat «выключает» игровой фильтр

FLOWSEAL_API = "https://api.github.com/repos/Flowseal/zapret-discord-youtube/releases/latest"
ZAPRET_API = "https://api.github.com/repos/bol-van/zapret/releases/latest"
ARCH = {"x86_64": "linux-x86_64", "aarch64": "linux-arm64", "armv7l": "linux-arm", "i686": "linux-x86"}

# свои файлы при обновлении не трогаем
KEEP = {"lists/list-general-user.txt", "lists/list-exclude-user.txt", "lists/ipset-exclude-user.txt",
        "lists/ipset-all.txt", "lists/ipset-all.txt.backup", "bin/ACTIVE_DISCORD_UDP.bin", "bin/ACTIVE_GAME_UDP.bin"}


# --- загрузка ---

def fetch_json(url):
    req = urllib.request.Request(url, headers={"User-Agent": "zapret-linux"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)


def download_tar(api, tmp):
    rel = fetch_json(api)
    url = next(a["browser_download_url"] for a in rel["assets"]
               if a["name"].endswith(".tar.gz") and "openwrt" not in a["name"])
    print(f"Скачиваю {url.rsplit('/', 1)[1]}…")
    os.makedirs(tmp, exist_ok=True)
    path = os.path.join(tmp, "a.tar.gz")
    urllib.request.urlretrieve(url, path)
    out = os.path.join(tmp, "x")
    with tarfile.open(path) as t:
        t.extractall(out)
    # в архиве одна папка с версией
    items = os.listdir(out)
    return rel["tag_name"], os.path.join(out, items[0]) if len(items) == 1 else out


def install(update=False):
    arch = ARCH.get(platform.machine())
    if not arch:
        sys.exit(f"Неизвестная архитектура {platform.machine()}")
    with tempfile.TemporaryDirectory() as tmp:
        tag, src = download_tar(FLOWSEAL_API, os.path.join(tmp, "f"))
        if update:
            new = {f for f in os.listdir(src) if f.endswith(".bat")}
            for f in os.listdir(ROOT):
                if f.endswith(".bat") and f not in new:
                    os.remove(os.path.join(ROOT, f))
        for d, _, files in os.walk(src):
            for f in files:
                rel = os.path.relpath(os.path.join(d, f), src)
                dst = os.path.join(ROOT, rel)
                if update and rel in KEEP and os.path.exists(dst):
                    continue
                os.makedirs(os.path.dirname(dst), exist_ok=True)
                shutil.copy(os.path.join(d, f), dst)
        ztag, zsrc = download_tar(ZAPRET_API, os.path.join(tmp, "z"))
        shutil.copy(os.path.join(zsrc, "binaries", arch, "nfqws"), NFQWS)
        os.chmod(NFQWS, 0o755)
    if os.path.abspath(__file__) != SELF:
        shutil.copy(os.path.abspath(__file__), SELF)
    ensure_user_lists()
    # nfqws сбрасывает root, файлы должны читаться всеми
    subprocess.run(["chmod", "-R", "a+rX", ROOT], check=True)
    os.chmod(SELF, 0o755)
    write_policy()
    print(f"Готово: стратегии {tag}, nfqws {ztag} в {ROOT}")


def write_policy():
    """Окно вызывает pkexec SELF: пароль спрашивается раз в несколько минут, а не на каждое действие."""
    if not os.path.isdir(os.path.dirname(POLICY)):
        return
    with open(POLICY, "w") as f:
        f.write(f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>
  <action id="pro.emptyprojects.zapret">
    <description>Управление zapret</description>
    <message>Для включения обхода блокировок нужен пароль администратора</message>
    <defaults>
      <allow_any>auth_admin</allow_any>
      <allow_inactive>auth_admin</allow_inactive>
      <allow_active>auth_admin_keep</allow_active>
    </defaults>
    <annotate key="org.freedesktop.policykit.exec.path">{SELF}</annotate>
  </action>
</policyconfig>
""")


def ensure_user_lists():
    for name, text in (("ipset-exclude-user.txt", "203.0.113.113/32\n"),
                       ("list-general-user.txt", "# Never leave this file empty\ndomain.example.abc\n"),
                       ("list-exclude-user.txt", "domain.example.abc\n")):
        if not os.path.exists(LISTS + name):
            with open(LISTS + name, "w") as f:
                f.write(text)


# --- стратегии ---

def strategies():
    key = lambda n: re.sub(r"\d+", lambda m: m.group().zfill(8), n).lower()
    names = [f[:-4] for f in os.listdir(ROOT) if f.endswith(".bat") and not f.startswith("service")]
    return sorted(names, key=key)


def unescape(text):
    """Экранирование cmd вне кавычек: ^x -> x."""
    out, quoted, i = [], False, 0
    while i < len(text):
        c = text[i]
        if c == '"':
            quoted = not quoted
        if c == "^" and not quoted and i + 1 < len(text):
            i += 1
            c = text[i]
        out.append(c)
        i += 1
    return "".join(out)


def build(name):
    """Аргументы nfqws и порты для nftables из general*.bat. --wf-* есть только у winws, из них берём порты."""
    with open(os.path.join(ROOT, name + ".bat"), encoding="utf-8") as f:
        lines = f.read().splitlines()
    start = next(i for i, l in enumerate(lines) if "winws.exe" in l.lower())
    line = lines[start]
    line = line[line.lower().index("winws.exe") + len("winws.exe"):].lstrip('"')
    parts, i = [], start
    while True:
        t = line.rstrip()
        cont = t.endswith("^")
        parts.append((t[:-1] if cont else t).strip())
        i += 1
        if not cont or i >= len(lines):
            break
        line = lines[i]

    text = unescape(" ".join(parts))
    for var, val in (("%BIN%", BIN), ("%LISTS%", LISTS), ("%~dp0", ROOT + "/"),
                     ("%GameFilterTCP%", GAME_OFF), ("%GameFilterUDP%", GAME_OFF), ("%GameFilter%", GAME_OFF)):
        text = re.sub(re.escape(var), lambda _: val, text, flags=re.I)
    left = re.search(r"%[A-Za-z_~][A-Za-z0-9_]*%", text)
    if left:
        raise ValueError(f"В {name}.bat неизвестная переменная {left.group()}")

    args, tcp, udp = [], "", ""
    for a in shlex.split(text.replace("\\", "/")):
        if a.startswith("--wf-tcp="):
            tcp = a.split("=", 1)[1]
        elif a.startswith("--wf-udp="):
            udp = a.split("=", 1)[1]
        elif not a.startswith("--wf-"):
            args.append(a)
    return args, tcp, udp


# --- nftables и nfqws ---

def nft(script):
    subprocess.run(["nft", "-f", "-"], input=script, text=True, check=True)


def nft_up(tcp, udp):
    nft_down()
    rules = [f"add table inet {TABLE}",
             f"add chain inet {TABLE} post {{ type filter hook postrouting priority 101; }}",
             f"add chain inet {TABLE} pre {{ type filter hook prerouting priority -99; }}",
             f"add chain inet {TABLE} predefrag {{ type filter hook output priority -401; }}",
             f"add rule inet {TABLE} predefrag mark and {MARK} != 0 notrack"]
    for proto, ports in (("tcp", tcp), ("udp", udp)):
        if ports:
            rules.append(f"add rule inet {TABLE} post {proto} dport {{ {ports} }} ct original packets 1-9 "
                         f"mark and {MARK} == 0 queue num {QNUM} bypass")
    if tcp:
        rules.append(f"add rule inet {TABLE} pre tcp sport {{ {tcp} }} ct reply packets 1-3 queue num {QNUM} bypass")
    nft("\n".join(rules) + "\n")


def nft_down():
    subprocess.run(["nft", "delete", "table", "inet", TABLE], stderr=subprocess.DEVNULL)


def start(name, quiet=False):
    args, tcp, udp = build(name)
    nft_up(tcp, udp)
    out = subprocess.DEVNULL if quiet else None
    p = subprocess.Popen([NFQWS, f"--qnum={QNUM}"] + args, cwd=BIN, stdout=out, stderr=out)
    time.sleep(1)
    if p.poll() is not None:
        nft_down()
        return None
    return p


def stop(p):
    if p and p.poll() is None:
        p.terminate()
        try:
            p.wait(3)
        except subprocess.TimeoutExpired:
            p.kill()
    nft_down()


def run(name):
    signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
    p = start(name)
    if not p:
        sys.exit(f"nfqws не запустился со стратегией {name}")
    print(f"Работает {name}. Ctrl+C — остановить.")
    try:
        p.wait()
    except KeyboardInterrupt:
        pass
    finally:
        stop(p)


# --- подбор (как «Run Tests → standard» в service.bat) ---

TESTS = (("HTTP", ["--http1.1"]), ("TLS1.2", ["--tlsv1.2", "--tls-max", "1.2"]), ("TLS1.3", ["--tlsv1.3", "--tls-max", "1.3"]))


def targets():
    result = []
    path = ROOT + "/utils/targets.txt"
    if os.path.exists(path):
        for line in open(path, encoding="utf-8"):
            m = re.match(r'^\s*(\w+)\s*=\s*"(.*)"\s*$', line)
            if m:
                result.append((m.group(1), m.group(2)))
    return result or [("DiscordMain", "https://discord.com"), ("YouTubeWeb", "https://www.youtube.com")]


def curl(url, extra):
    try:
        p = subprocess.run(["curl", "-I", "-s", "-m", "4", "--connect-timeout", "2", "-o", "/dev/null",
                            "--show-error"] + extra + [url], capture_output=True, text=True, timeout=20)
    except subprocess.TimeoutExpired:
        return "ERROR"
    if re.search(r"Could not resolve host|certificate|self[- ]?signed", p.stderr, re.I):
        return "SSL"
    if p.returncode == 35 or re.search(r"not supported|unsupported|Unknown option", p.stderr, re.I):
        return "UNSUP"
    return "OK" if p.returncode == 0 else "ERROR"


def ping(host):
    p = subprocess.run(["ping", "-c", "1", "-W", "1", host], capture_output=True, text=True)
    m = re.search(r"time=([\d.]+)", p.stdout)
    return f"{float(m.group(1)):.0f} ms" if m else "Timeout"


def check(target):
    name, value = target
    if value.upper().startswith("PING:"):
        return name, [], ping(value[5:].strip())
    host = re.sub(r"/.*$", "", re.sub(r"^https?://", "", value))
    return name, [curl(value, t[1]) for t in TESTS], ping(host)


def test(batch=False):
    """batch — для окна: строки PROGRESS/RESULT/BEST, без вопросов; закрытый stdin — остановиться после текущей."""
    if not shutil.which("curl"):
        sys.exit("Нужен curl: sudo apt install curl")
    cancel = threading.Event()
    if batch:
        threading.Thread(target=lambda: (sys.stdin.read(), cancel.set()), daemon=True).start()
    was_active = service_active()
    if was_active:
        print("Останавливаю обход на время проверки")
        subprocess.run(["systemctl", "stop", SERVICE])
    names, tg, results = strategies(), targets(), []
    report = [f"Проверка {datetime.now():%Y-%m-%d %H:%M}"]
    try:
        for i, name in enumerate(names, 1):
            if cancel.is_set():
                break
            if batch:
                print(f"PROGRESS\t{i}\t{len(names)}\t{name}", flush=True)
            else:
                print(f"[{i}/{len(names)}] {name:<28}", end=" ", flush=True)
            try:
                p = start(name, quiet=True)
            except (ValueError, OSError, subprocess.CalledProcessError) as e:
                print(e)
                p = None
            if not p:
                print(f"RESULT\t{name}\t-1\t0\t0\t0" if batch else "не запустился", flush=True)
                report.append(f"\n{name}: не запустился")
                continue
            try:
                with ThreadPoolExecutor(16) as ex:
                    checks = list(ex.map(check, tg))
            finally:
                stop(p)
            ok = sum(h.count("OK") for _, h, _ in checks)
            total = sum(len(h) for _, h, _ in checks)
            pings = sum(1 for *_, pg in checks if pg != "Timeout")
            results.append((ok, pings, name))
            print(f"RESULT\t{name}\t{ok}\t{total}\t{pings}\t{len(checks)}" if batch
                  else f"OK {ok}/{total}, ping {pings}/{len(checks)}", flush=True)
            report.append(f"\n{name}: OK {ok}/{total}, ping {pings}/{len(checks)}")
            report += [f"  {n:<22} {' '.join(f'{t[0]}:{h}' for t, h in zip(TESTS, hs))} ping:{pg}"
                       for n, hs, pg in checks]
    except KeyboardInterrupt:
        print("\nПрервано")

    best = max((r for r in results if r[0] > 0), key=lambda r: r[:2], default=None)
    report.append(f"\nЛучшая: {best[2]}" if best else "\nНи одна стратегия не помогла")
    os.makedirs(ROOT + "/utils/test results", exist_ok=True)
    path = f"{ROOT}/utils/test results/test-{datetime.now():%Y%m%d-%H%M%S}.txt"
    with open(path, "w", encoding="utf-8") as f:
        f.write("\n".join(report) + "\n")
    print(f"\nОтчёт: {path}")
    if batch:
        print(f"BEST\t{best[2] if best else ''}\t{path}", flush=True)
    elif not best:
        print("Ни одна стратегия не помогла")
    else:
        print(f"Лучшая: {best[2]} (OK {best[0]}, ping {best[1]})")
        if ask("Поставить её в автозапуск?"):
            enable(best[2])
            return
    if was_active:
        subprocess.run(["systemctl", "start", SERVICE])


# --- автозапуск (systemd) ---

def service_active():
    return bool(shutil.which("systemctl")) and \
        subprocess.run(["systemctl", "is-active", "--quiet", SERVICE]).returncode == 0


def service_strategy():
    if not os.path.exists(UNIT):
        return None
    m = re.search(r'zapret\.py run "([^"]+)"', open(UNIT).read())
    return m and m.group(1)


def write_unit(name):
    build(name)   # проверить, что разбирается
    with open(UNIT, "w") as f:
        f.write(f"""[Unit]
Description=zapret-discord-youtube ({name})
Wants=network-online.target
After=network-online.target

[Service]
ExecStart=/usr/bin/python3 {SELF} run "{name}"
ExecStopPost=-/usr/sbin/nft delete table inet {TABLE}
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
""")
    subprocess.run(["systemctl", "daemon-reload"])


def start_service(name):
    write_unit(name)
    subprocess.run(["systemctl", "restart", SERVICE])
    time.sleep(2)
    if not service_active():
        sys.exit(f"{name} не запустился, см. journalctl -u {SERVICE}")
    print(f"Работает {name}")


def enable(name):
    write_unit(name)
    subprocess.run(["systemctl", "enable", SERVICE], stderr=subprocess.DEVNULL)
    start_service(name)


def disable():
    if os.path.exists(UNIT):
        subprocess.run(["systemctl", "disable", "--now", SERVICE], stderr=subprocess.DEVNULL)
        os.remove(UNIT)
        subprocess.run(["systemctl", "daemon-reload"])
    nft_down()
    print("Автозапуск выключен")


# --- меню ---

def ask(q):
    return input(f"{q} [y/N] ").strip().lower() in ("y", "д", "yes", "да")


def pick():
    names = strategies()
    for i, n in enumerate(names, 1):
        print(f"{i:>3}. {n}")
    s = input("Номер стратегии: ").strip()
    return names[int(s) - 1] if s.isdigit() and 0 < int(s) <= len(names) else None


def menu():
    while True:
        cur = service_strategy()
        state = f"{cur}, {'работает' if service_active() else 'не работает'}" if cur else "выключен"
        print(f"\nzapret-discord-youtube для Linux. Автозапуск: {state}")
        print("1. Подобрать стратегию\n2. Запустить стратегию (до Ctrl+C)\n3. Включить автозапуск\n"
              "4. Выключить автозапуск\n5. Обновить zapret\n0. Выход")
        c = input("> ").strip()
        if c == "1":
            test()
        elif c in ("2", "3"):
            name = pick()
            if not name:
                continue
            if c == "3":
                enable(name)
            elif service_active():
                print("Работает автозапуск, сначала выключите его (4)")
            else:
                run(name)
        elif c == "4":
            disable()
        elif c == "5":
            install(update=True)
            if service_active():
                subprocess.run(["systemctl", "restart", SERVICE])
        elif c == "0":
            return


def main():
    if os.geteuid() != 0:
        os.execvp("sudo", ["sudo", sys.executable, os.path.abspath(__file__)] + sys.argv[1:])
    if not shutil.which("nft"):
        sys.exit("Нужен nftables: sudo apt install nftables")
    if not os.path.exists(NFQWS):
        install()
    elif not os.path.exists(POLICY) and os.path.exists(SELF):
        os.chmod(SELF, 0o755)
        write_policy()
    if subprocess.run(["pgrep", "-x", "nfqws"], capture_output=True).returncode == 0 and not service_active():
        print("Внимание: уже запущен nfqws (другой zapret?), он может мешать")

    cmd, arg = (sys.argv + [None, None])[1:3]
    try:
        if cmd == "install":
            if os.path.exists(NFQWS):
                install(update=True)
        elif cmd is None:
            menu()
        elif cmd == "test":
            test(batch=arg == "--batch")
        elif cmd == "start" and arg:
            start_service(arg)
        elif cmd == "stop":
            subprocess.run(["systemctl", "stop", SERVICE])
        elif cmd == "autostart" and arg in ("on", "off"):
            if arg == "on" and not os.path.exists(UNIT):
                sys.exit("Сначала включите обход")
            subprocess.run(["systemctl", "enable" if arg == "on" else "disable", SERVICE], stderr=subprocess.DEVNULL)
        elif cmd == "run" and arg:
            run(arg)
        elif cmd == "enable" and arg:
            enable(arg)
        elif cmd == "disable":
            disable()
        elif cmd == "update":
            install(update=True)
        else:
            print(__doc__)
    except KeyboardInterrupt:
        print()


if __name__ == "__main__":
    main()
