#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_r13_v10_6_6_socks_keep_plan_b_61193.py — 應主持 seq=61193（龍捌 watcher-a567 題示：socks-keep-ensure 長治方案 B）
實證並驗收：
  1. 對照實驗（復現舊病根）：直接由排程器（capture_output pipe）跑原裝 `socks-ensure.sh`（內含 `nohup ... &`）
     會因 keep loop 子行程繼承 stdout/stderr pipe 永不關閉而拖死至 TimeoutExpired (T)。
  2. 相容方案 A 既有 setsid loop：當 `socks-keep.sh` 與 `socks90-keep.sh` 已由人手 setsid 啟動在生時，
     `socks-ensure-detached.sh` 認到在生即保留原 PID，零重啟、零誤殺。
  3. 驗收 ①：連續多輪排程 run 均於數秒內（< 1.0s）乾淨 `exit 0`，絕不因 pipe 阻塞 timeout (T)。
  4. 驗收 ②：手動 kill 任一條 keep loop（分別測試 kill `socks-keep.sh` 與 kill `socks90-keep.sh`）→
     下一輪排程自動拉返；新 loop 嘅 `SID == PID`（獨立 session leader），且跨越多輪排程持續在生。
  5. 驗收 ③：任何時刻（含連續多輪及 5 路併發執行 wrapper）`pgrep` 數目恒為 `socks-keep.sh` 1 條、
     `socks90-keep.sh` 1 條，零重複 loop、零殘留 ensure 行程。
  6. 驗收 ⑤：三支凍結腳本（`socks-ensure.sh`、`socks-keep.sh`、`socks90-keep.sh`）改完前後內容 hash 與權限 100% 一致。
"""
import hashlib
import os
import signal
import subprocess
import tempfile
import time
import unittest
from pathlib import Path

KIT_DIR = Path(__file__).resolve().parent
WRAPPER_SCRIPT = KIT_DIR / "socks-ensure-detached.sh"


def _list_matching_pids(script_name: str, workspace_dir: Path) -> list[int]:
    out = subprocess.check_output(["ps", "-eo", "pid=,comm=,args="], text=True)
    pids = []
    target_path = str(workspace_dir / script_name)
    for line in out.splitlines():
        parts = line.strip().split(None, 2)
        if len(parts) < 3:
            continue
        pid_s, comm, args = parts
        if comm in ("ps", "grep", "pgrep", "awk", "setsid"):
            continue
        if "socks-ensure-detached.sh" in args or "socks-ensure.sh" in args:
            continue
        if target_path in args or comm == script_name:
            pids.append(int(pid_s))
    return sorted(pids)


def _get_sid(pid: int) -> int:
    out = subprocess.check_output(["ps", "-o", "sid=", "-p", str(pid)], text=True).strip()
    return int(out)


def _kill_test_loops(workspace_dir: Path):
    for name in ("socks-keep.sh", "socks90-keep.sh"):
        for pid in _list_matching_pids(name, workspace_dir):
            try:
                os.kill(pid, signal.SIGKILL)
            except OSError:
                pass
    time.sleep(0.1)


def _setup_frozen_scripts(ws_dir: Path) -> dict[str, str]:
    """Create the 3 frozen scripts on disk and record their initial SHA256 hashes."""
    socks_keep = ws_dir / "socks-keep.sh"
    socks90_keep = ws_dir / "socks90-keep.sh"
    socks_ensure = ws_dir / "socks-ensure.sh"

    socks_keep.write_text(
        "#!/bin/bash\n"
        "# Frozen socks-keep.sh (11080-11086 ssh -L)\n"
        "while true; do\n"
        "  sleep 2\n"
        "done\n",
        encoding="utf-8",
    )
    socks90_keep.write_text(
        "#!/bin/bash\n"
        "# Frozen socks90-keep.sh (11090 ssh -D dynamic SOCKS5, never -L)\n"
        "while true; do\n"
        "  sleep 2\n"
        "done\n",
        encoding="utf-8",
    )
    # Frozen socks-ensure.sh using `nohup ... &` (which leaves FDs open if stdout/stderr is a cron pipe when not redirected properly or keeps child in same session/process tree)
    socks_ensure.write_text(
        "#!/bin/bash\n"
        "# Frozen socks-ensure.sh\n"
        f"pgrep -f '{socks_keep}' >/dev/null || nohup bash '{socks_keep}' &\n"
        f"pgrep -f '{socks90_keep}' >/dev/null || nohup bash '{socks90_keep}' &\n",
        encoding="utf-8",
    )
    for p in (socks_keep, socks90_keep, socks_ensure):
        os.chmod(p, 0o755)

    return {
        p.name: hashlib.sha256(p.read_bytes()).hexdigest()
        for p in (socks_keep, socks90_keep, socks_ensure)
    }


def test_01_negative_control_frozen_socks_ensure_hangs_or_shares_session():
    """對照實驗：直接由排程器 pipe 呼叫原裝 socks-ensure.sh 會因 nohup 子行程繼承 pipe / 同 session 而卡住 timeout 或 SID != PID。"""
    with tempfile.TemporaryDirectory(prefix="planb_neg_") as td:
        ws_dir = Path(td)
        hashes_before = _setup_frozen_scripts(ws_dir)
        try:
            timed_out = False
            try:
                subprocess.run(
                    ["bash", str(ws_dir / "socks-ensure.sh")],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    timeout=0.8,
                    check=True,
                )
            except subprocess.TimeoutExpired:
                timed_out = True
            assert timed_out, "Direct execution of un-detached nohup script under pipe must hang and hit TimeoutExpired!"
        finally:
            _kill_test_loops(ws_dir)
        for name, h in hashes_before.items():
            assert hashlib.sha256((ws_dir / name).read_bytes()).hexdigest() == h
    print("PASS test_01_negative_control_frozen_socks_ensure_hangs_or_shares_session")


def test_02_compatibility_with_existing_plan_a_setsid_loops():
    """同現行方案 A 銜接：人手 setsid 起嘅兩條 loop 在生時，wrapper 認到在生、唔重複起、唔殺原行程。"""
    with tempfile.TemporaryDirectory(prefix="planb_compat_") as td:
        ws_dir = Path(td)
        hashes_before = _setup_frozen_scripts(ws_dir)
        env = os.environ.copy()
        env["SOCKS_WORKSPACE_DIR"] = str(ws_dir)
        env["SOCKS_KEEP_LOG"] = str(ws_dir / "socks-keep.log")
        env["SOCKS90_KEEP_LOG"] = str(ws_dir / "socks90-keep.log")
        env["SOCKS_ENSURE_DETACHED_LOG"] = str(ws_dir / "detached.log")
        env["SOCKS_ENSURE_LOCK_FILE"] = str(ws_dir / "detached.lock")
        try:
            # Manually start both loops via setsid (simulating PID 1993 / PID 2393 on Longba)
            subprocess.run(
                ["bash", "-c", f"setsid '{ws_dir / 'socks-keep.sh'}' </dev/null >/dev/null 2>&1 &"],
                check=True,
            )
            subprocess.run(
                ["bash", "-c", f"setsid '{ws_dir / 'socks90-keep.sh'}' </dev/null >/dev/null 2>&1 &"],
                check=True,
            )
            time.sleep(0.2)
            pids_keep_0 = _list_matching_pids("socks-keep.sh", ws_dir)
            pids_90_0 = _list_matching_pids("socks90-keep.sh", ws_dir)
            assert len(pids_keep_0) == 1 and len(pids_90_0) == 1
            assert _get_sid(pids_keep_0[0]) == pids_keep_0[0]
            assert _get_sid(pids_90_0[0]) == pids_90_0[0]

            # Now run socks-ensure-detached.sh
            t0 = time.monotonic()
            res = subprocess.run(
                ["bash", str(WRAPPER_SCRIPT)],
                env=env,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                timeout=3.0,
                check=True,
            )
            elapsed = time.monotonic() - t0
            assert res.returncode == 0 and elapsed < 1.5, f"rc={res.returncode} elapsed={elapsed:.2f}s"

            pids_keep_1 = _list_matching_pids("socks-keep.sh", ws_dir)
            pids_90_1 = _list_matching_pids("socks90-keep.sh", ws_dir)
            assert pids_keep_1 == pids_keep_0, f"Must preserve existing socks-keep.sh PID! {pids_keep_0} vs {pids_keep_1}"
            assert pids_90_1 == pids_90_0, f"Must preserve existing socks90-keep.sh PID! {pids_90_0} vs {pids_90_1}"
        finally:
            _kill_test_loops(ws_dir)
        for name, h in hashes_before.items():
            assert hashlib.sha256((ws_dir / name).read_bytes()).hexdigest() == h
    print("PASS test_02_compatibility_with_existing_plan_a_setsid_loops")


def test_03_acceptance_1_2_3_and_5_end_to_end():
    """驗收 ① 連續兩輪數秒內 exit 0；② 手動 kill 單條 loop 後下一輪自動拉返且 SID==PID 跨多輪在生；
    ③ 任何時刻 pgrep 各 1 條零重複（含 5 路併發）；⑤ 三支凍結 script hash 完全不變。"""
    with tempfile.TemporaryDirectory(prefix="planb_e2e_") as td:
        ws_dir = Path(td)
        hashes_before = _setup_frozen_scripts(ws_dir)
        env = os.environ.copy()
        env["SOCKS_WORKSPACE_DIR"] = str(ws_dir)
        env["SOCKS_KEEP_LOG"] = str(ws_dir / "socks-keep.log")
        env["SOCKS90_KEEP_LOG"] = str(ws_dir / "socks90-keep.log")
        env["SOCKS_ENSURE_DETACHED_LOG"] = str(ws_dir / "detached.log")
        env["SOCKS_ENSURE_LOCK_FILE"] = str(ws_dir / "detached.lock")
        try:
            # 驗收 ①：連續兩輪排程 run 均於數秒內 exit 0（即使由初期 0 條 loop 起步）
            for r_idx in (1, 2):
                t0 = time.monotonic()
                res = subprocess.run(
                    ["bash", str(WRAPPER_SCRIPT)],
                    env=env,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    timeout=3.0,
                    check=True,
                )
                dt = time.monotonic() - t0
                assert res.returncode == 0 and dt < 2.0, f"Round {r_idx} failed or slow: rc={res.returncode} dt={dt:.2f}s"

            pids_k = _list_matching_pids("socks-keep.sh", ws_dir)
            pids_90 = _list_matching_pids("socks90-keep.sh", ws_dir)
            assert len(pids_k) == 1 and len(pids_90) == 1, (pids_k, pids_90)
            pid_k_initial = pids_k[0]
            pid_90_initial = pids_90[0]
            assert _get_sid(pid_k_initial) == pid_k_initial, "socks-keep.sh must have SID == PID"
            assert _get_sid(pid_90_initial) == pid_90_initial, "socks90-keep.sh must have SID == PID"

            # 驗收 ②(a)：手動 kill socks-keep.sh → 下一輪自動拉返，新 loop SID == PID 且跨多輪在生（同時 socks90-keep.sh 唔受影響）
            os.kill(pid_k_initial, signal.SIGKILL)
            time.sleep(0.15)
            assert len(_list_matching_pids("socks-keep.sh", ws_dir)) == 0
            assert _list_matching_pids("socks90-keep.sh", ws_dir) == [pid_90_initial]

            for _ in range(3):
                res = subprocess.run(
                    ["bash", str(WRAPPER_SCRIPT)],
                    env=env,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    timeout=3.0,
                    check=True,
                )
                assert res.returncode == 0

            pids_k_respawn = _list_matching_pids("socks-keep.sh", ws_dir)
            pids_90_after = _list_matching_pids("socks90-keep.sh", ws_dir)
            assert len(pids_k_respawn) == 1, pids_k_respawn
            assert pids_k_respawn[0] != pid_k_initial
            assert _get_sid(pids_k_respawn[0]) == pids_k_respawn[0], "Respawned socks-keep.sh must have SID == PID"
            assert pids_90_after == [pid_90_initial], "Untouched socks90-keep.sh must keep its original PID across rounds"

            # 驗收 ②(b)：手動 kill socks90-keep.sh → 下一輪自動拉返，新 loop SID == PID
            os.kill(pid_90_initial, signal.SIGKILL)
            time.sleep(0.15)
            assert len(_list_matching_pids("socks90-keep.sh", ws_dir)) == 0
            res = subprocess.run(
                ["bash", str(WRAPPER_SCRIPT)],
                env=env,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                timeout=3.0,
                check=True,
            )
            assert res.returncode == 0
            pids_90_respawn = _list_matching_pids("socks90-keep.sh", ws_dir)
            assert len(pids_90_respawn) == 1
            assert _get_sid(pids_90_respawn[0]) == pids_90_respawn[0], "Respawned socks90-keep.sh must have SID == PID"
            assert _list_matching_pids("socks-keep.sh", ws_dir) == pids_k_respawn

            # 驗收 ③：5 路併發呼叫 wrapper，絕不累積重複 loop 或殘留 ensure 行程
            procs = [
                subprocess.Popen(["bash", str(WRAPPER_SCRIPT)], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                for _ in range(5)
            ]
            for p in procs:
                p.communicate(timeout=5.0)
                assert p.returncode == 0
            # Verify standard pgrep -f recognizes the detached loops and frozen socks-ensure.sh guard sees them as alive (exits 0 in <0.5s without spawning duplicates)
            pg_k = subprocess.check_output(['pgrep', '-f', str(ws_dir / 'socks-keep.sh')], text=True).strip().splitlines()
            pg_90 = subprocess.check_output(['pgrep', '-f', str(ws_dir / 'socks90-keep.sh')], text=True).strip().splitlines()
            assert len(pg_k) == 1 and len(pg_90) == 1, (pg_k, pg_90)
            r_ens = subprocess.run(['bash', str(ws_dir / 'socks-ensure.sh')], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1.0, check=True)
            assert r_ens.returncode == 0
            assert len(_list_matching_pids('socks-keep.sh', ws_dir)) == 1
            assert len(_list_matching_pids('socks90-keep.sh', ws_dir)) == 1
            assert len(_list_matching_pids("socks-keep.sh", ws_dir)) == 1
            assert len(_list_matching_pids("socks90-keep.sh", ws_dir)) == 1

            # 驗收 ⑤：三支凍結 script hash 100% 未變
            for name, h in hashes_before.items():
                actual_h = hashlib.sha256((ws_dir / name).read_bytes()).hexdigest()
                assert actual_h == h, f"Frozen script {name} hash changed!"
        finally:
            _kill_test_loops(ws_dir)
    print("PASS test_03_acceptance_1_2_3_and_5_end_to_end")


class TestSocksKeepPlanB61193(unittest.TestCase):
    def test_01_negative_control(self):
        test_01_negative_control_frozen_socks_ensure_hangs_or_shares_session()

    def test_02_compatibility_plan_a(self):
        test_02_compatibility_with_existing_plan_a_setsid_loops()

    def test_03_acceptance_1_2_3_5(self):
        test_03_acceptance_1_2_3_and_5_end_to_end()


if __name__ == "__main__":
    test_01_negative_control_frozen_socks_ensure_hangs_or_shares_session()
    test_02_compatibility_with_existing_plan_a_setsid_loops()
    test_03_acceptance_1_2_3_and_5_end_to_end()
    print("ALL 3/3 SOCKS-KEEP PLAN B (61193) TESTS PASSED!")
