"""SSH 執行任意指令(吃多行,用 \\n 分隔)。"""

import sys
from pathlib import Path

try:
    sys.stdout.reconfigure(encoding="utf-8")
except (AttributeError, ValueError):
    pass

import paramiko

SECRETS = Path(r"C:\Users\user\Desktop\Coba\deploy_secrets.txt")
secrets = {}
for line in SECRETS.read_text(encoding="utf-8").splitlines():
    line = line.strip()
    if "=" in line and not line.startswith("#"):
        k, v = line.split("=", 1)
        secrets[k.strip()] = v.strip()


def run(client, cmd: str, timeout: int = 60) -> tuple[int, str, str]:
    stdin, stdout, stderr = client.exec_command(cmd, timeout=timeout)
    out = stdout.read().decode("utf-8", errors="replace")
    err = stderr.read().decode("utf-8", errors="replace")
    code = stdout.channel.recv_exit_status()
    return code, out, err


def sudo_run(client, cmd: str, password: str, timeout: int = 120) -> tuple[int, str, str]:
    """sudo 跑(密碼自動透過 stdin 餵進去)。"""
    full = f"echo '{password}' | sudo -S sh -c {repr(cmd)}"
    return run(client, full, timeout=timeout)


def main():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(
        hostname=secrets["NAS_HOST"],
        port=int(secrets["NAS_PORT"]),
        username=secrets["NAS_USER"],
        password=secrets["NAS_PASSWORD"],
        timeout=10,
        allow_agent=False,
        look_for_keys=False,
    )

    cmds = sys.argv[1:] if len(sys.argv) > 1 else [
        # 探測環境
        "ls /volume1/ 2>/dev/null",
        "uname -m",
        "ls /var/packages | grep -i python",
        "ls /var/packages | head -30",
        "which python3 python3.10 python3.11 python3.12 python3.13 2>&1 || true",
        "ls /usr/local/python*/bin/python* 2>/dev/null || echo 'no /usr/local/python*'",
        "df -h /volume1 | tail -1",
    ]
    for cmd in cmds:
        print(f"\n$ {cmd}")
        code, out, err = run(client, cmd)
        if out:
            print(out.rstrip())
        if err:
            print(f"[stderr] {err.rstrip()}")
        if code != 0:
            print(f"[exit {code}]")

    client.close()


if __name__ == "__main__":
    main()
