#!/bin/bash
# 2520 部署脚本 - 将Jetson Agent部署到Jetson设备
# 用法: ./deploy.sh [JETSON_IP] [USER]
# 默认: JETSON_IP=192.168.1.108  USER=nvidia
#
# 架构: PC端运行Run_2520.py(主控), Jetson端运行jetson_agent.py(代理)
# 此脚本仅部署Jetson端代理

JETSON_IP="${1:-192.168.1.108}"
JETSON_USER="${2:-nvidia}"
REMOTE_DIR="/home/nvidia/2520Fuzz"

echo "========================================="
echo "  2520 - Jetson Agent 部署"
echo "========================================="
echo "目标: ${JETSON_USER}@${JETSON_IP}"
echo "目录: ${REMOTE_DIR}"
echo ""

# 检查SSH连接
echo "[1/5] 检查SSH连接..."
ssh -o ConnectTimeout=5 -o BatchMode=yes ${JETSON_USER}@${JETSON_IP} "echo OK" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "SSH密钥认证失败，尝试密码认证..."
    if command -v sshpass &> /dev/null; then
        export SSHPASS="nvidia"
        sshpass -e ssh -o ConnectTimeout=5 ${JETSON_USER}@${JETSON_IP} "echo OK"
        if [ $? -ne 0 ]; then
            echo "错误: 无法连接到Jetson设备"
            exit 1
        fi
        SCP_CMD="sshpass -e scp"
        SSH_CMD="sshpass -e ssh"
    else
        echo "错误: 需要sshpass工具 (apt install sshpass) 或配置SSH密钥认证"
        exit 1
    fi
else
    SCP_CMD="scp"
    SSH_CMD="ssh"
fi

# 创建远程目录
echo "[2/5] 创建远程目录..."
$SSH_CMD ${JETSON_USER}@${JETSON_IP} "mkdir -p ${REMOTE_DIR}/fuzz_workspace ${REMOTE_DIR}/crash_records"

# 上传Jetson Agent
echo "[3/5] 上传jetson_agent.py..."
SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
$SCP_CMD "${SCRIPT_DIR}/jetson/jetson_agent.py" ${JETSON_USER}@${JETSON_IP}:${REMOTE_DIR}/

# 设置权限并检查Python3
echo "[4/5] 检查Python3环境..."
$SSH_CMD ${JETSON_USER}@${JETSON_IP} "chmod +x ${REMOTE_DIR}/jetson_agent.py && python3 --version"

# 停止旧进程(如果存在)并启动新进程
echo "[5/5] 启动Jetson Agent..."
$SSH_CMD ${JETSON_USER}@${JETSON_IP} "pkill -f jetson_agent.py 2>/dev/null; sleep 1; cd ${REMOTE_DIR} && nohup python3 jetson_agent.py > agent.log 2>&1 &"
sleep 2

# 验证Agent服务
echo ""
echo "验证Jetson Agent..."
$SSH_CMD ${JETSON_USER}@${JETSON_IP} "curl -s http://localhost:7886/api/status" 2>/dev/null
if [ $? -eq 0 ]; then
    echo ""
    echo "========================================="
    echo "  Jetson Agent 部署成功!"
    echo "========================================="
    echo ""
    echo "Jetson Agent: http://${JETSON_IP}:7886/"
    echo "Agent日志: ssh ${JETSON_USER}@${JETSON_IP} 'tail -f ${REMOTE_DIR}/agent.log'"
    echo "停止Agent: ssh ${JETSON_USER}@${JETSON_IP} 'pkill -f jetson_agent.py'"
    echo ""
    echo "========================================="
    echo "  PC端启动方式"
    echo "========================================="
    echo "cd ${SCRIPT_DIR}"
    echo "python server/Run_2520.py"
    echo ""
    echo "浏览器访问: http://127.0.0.1:7885/"
else
    echo "警告: Agent可能未正常启动，请检查日志"
    echo "ssh ${JETSON_USER}@${JETSON_IP} 'cat ${REMOTE_DIR}/agent.log'"
fi
