#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
2520 Jetson Agent 部署工具 (Windows版)
使用paramiko通过SSH部署jetson_agent.py到Jetson设备
如果没有paramiko，则提供手动部署指令
"""

import os
import sys
import json

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
AGENT_FILE = os.path.join(SCRIPT_DIR, "..", "jetson", "jetson_agent.py")

# Jetson连接配置
JETSON_HOST = "192.168.1.108"
JETSON_USER = "nvidia"
JETSON_PASS = "nvidia"
REMOTE_DIR = "/home/nvidia/2520Fuzz"


def deploy_with_paramiko():
    """使用paramiko部署"""
    try:
        import paramiko
    except ImportError:
        print("[!] paramiko未安装，尝试安装...")
        os.system(f"{sys.executable} -m pip install paramiko -q")
        try:
            import paramiko
        except ImportError:
            print("[X] paramiko安装失败，请手动安装: pip install paramiko")
            return False

    print(f"[1/6] 连接到 {JETSON_USER}@{JETSON_HOST}...")

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(JETSON_HOST, username=JETSON_USER, password=JETSON_PASS, timeout=10)
        print("    连接成功!")
    except Exception as e:
        print(f"[X] 连接失败: {e}")
        return False

    # 创建远程目录
    print("[2/6] 创建远程目录...")
    cmds = [
        f"mkdir -p {REMOTE_DIR}/fuzz_workspace",
        f"mkdir -p {REMOTE_DIR}/crash_records",
    ]
    for cmd in cmds:
        ssh.exec_command(cmd)
    print("    目录创建完成")

    # 上传jetson_agent.py
    print("[3/6] 上传jetson_agent.py...")
    sftp = ssh.open_sftp()
    remote_path = f"{REMOTE_DIR}/jetson_agent.py"
    try:
        sftp.put(AGENT_FILE, remote_path)
        print(f"    上传成功: {remote_path}")
    except Exception as e:
        print(f"[X] 上传失败: {e}")
        sftp.close()
        ssh.close()
        return False
    sftp.close()

    # 设置权限
    print("[4/6] 设置权限...")
    ssh.exec_command(f"chmod +x {REMOTE_DIR}/jetson_agent.py")

    # 检查Python3
    print("[5/6] 检查Python3环境...")
    stdin, stdout, stderr = ssh.exec_command("python3 --version")
    py_ver = stdout.read().decode().strip()
    print(f"    {py_ver}")

    # 停止旧进程并启动Agent
    print("[6/6] 启动Jetson Agent...")
    ssh.exec_command(f"pkill -f jetson_agent.py 2>/dev/null")
    import time
    time.sleep(1)
    ssh.exec_command(
        f"cd {REMOTE_DIR} && nohup python3 jetson_agent.py > agent.log 2>&1 &"
    )
    time.sleep(2)

    # 验证
    print("\n验证Agent服务...")
    stdin, stdout, stderr = ssh.exec_command("curl -s http://localhost:7886/api/status")
    result = stdout.read().decode().strip()

    ssh.close()

    if result:
        print(f"    Agent响应: {result[:200]}")
        print("\n" + "=" * 50)
        print("  Jetson Agent 部署成功!")
        print("=" * 50)
        print(f"  Agent地址: http://{JETSON_HOST}:7886/")
        print(f"  Agent日志: ssh {JETSON_USER}@{JETSON_HOST} 'tail -f {REMOTE_DIR}/agent.log'")
        print(f"  停止Agent: ssh {JETSON_USER}@{JETSON_HOST} 'pkill -f jetson_agent.py'")
        print()
        print("  PC端启动: cd 2520Fuzz && python server\\Run_2520.py")
        print("  浏览器:   http://127.0.0.1:7885/")
        return True
    else:
        print("[!] Agent可能未正常启动，请检查日志")
        return False


def print_manual_steps():
    """打印手动部署步骤"""
    print("\n" + "=" * 60)
    print("  手动部署步骤")
    print("=" * 60)
    print(f"""
1. 打开终端，SSH连接到Jetson:
   ssh nvidia@{JETSON_HOST}
   密码: nvidia

2. 在Jetson上创建目录:
   mkdir -p {REMOTE_DIR}/fuzz_workspace
   mkdir -p {REMOTE_DIR}/crash_records

3. 在PC上新开一个终端，上传Agent:
   scp "{AGENT_FILE}" nvidia@{JETSON_HOST}:{REMOTE_DIR}/

4. 回到Jetson SSH终端，启动Agent:
   cd {REMOTE_DIR}
   python3 jetson_agent.py &

5. 验证Agent运行:
   curl http://localhost:7886/api/status

6. 在PC上启动主控服务:
   cd {SCRIPT_DIR}
   python server\\Run_2520.py

7. 浏览器访问:
   http://127.0.0.1:7885/
""")


if __name__ == "__main__":
    print("=" * 50)
    print("  2520 - Jetson Agent 部署工具")
    print("=" * 50)
    print(f"  目标: {JETSON_USER}@{JETSON_HOST}")
    print(f"  目录: {REMOTE_DIR}")
    print()

    # 检查agent文件是否存在
    if not os.path.exists(AGENT_FILE):
        print(f"[X] jetson_agent.py 不存在: {AGENT_FILE}")
        sys.exit(1)

    # 尝试自动部署
    success = deploy_with_paramiko()

    if not success:
        print_manual_steps()
