#!/usr/bin/env python3
"""Deploy Plan C dubbo-dev-proxy to 192.168.20.100 via SSH."""

import os
import stat
import sys

try:
    import paramiko
except ImportError:
    print("paramiko not installed, run: pip install paramiko")
    sys.exit(1)

HOST = "192.168.20.100"
USER = "root"
PASSWORD = "Zcloud@zcloud100"
LOCAL_DIR = os.path.dirname(os.path.abspath(__file__))
REMOTE_SRC = "/opt/dubbo-dev-proxy-src"


def main():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    print(f"Connecting to {HOST}...")
    client.connect(HOST, username=USER, password=PASSWORD, timeout=20)

    sftp = client.open_sftp()
    try:
        sftp.mkdir(REMOTE_SRC)
    except OSError:
        pass

    for name in os.listdir(LOCAL_DIR):
        if not (name.endswith(".sh") or name.endswith(".map")):
            continue
        local_path = os.path.join(LOCAL_DIR, name)
        remote_path = f"{REMOTE_SRC}/{name}"
        print(f"Upload {name}")
        sftp.put(local_path, remote_path)
        if name.endswith(".sh"):
            sftp.chmod(
                remote_path,
                stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH,
            )
    sftp.close()

    commands = [
        f"cd {REMOTE_SRC} && chmod +x *.sh && INSTALL_DIR=/opt/dubbo-dev-proxy bash dubbo-proxy-install.sh",
        "/opt/dubbo-dev-proxy/dubbo-proxy-status.sh",
        "ss -lntp | awk '/3208|32100/' | head -8",
        "nc -zv 127.0.0.1 32080 2>&1",
        "nc -zv 127.0.0.1 32084 2>&1",
    ]

    for cmd in commands:
        print(f"\n>>> {cmd}")
        stdin, stdout, stderr = client.exec_command(cmd, timeout=180)
        out = stdout.read().decode()
        err = stderr.read().decode()
        code = stdout.channel.recv_exit_status()
        if out:
            print(out)
        if err:
            print("STDERR:", err)
        print(f"EXIT {code}")
        if code != 0 and "dubbo-proxy-install" in cmd:
            client.close()
            sys.exit(code)

    client.close()
    print("\nDeploy finished.")


if __name__ == "__main__":
    main()
