#!/bin/bash
# verify-deadman.sh - 死手系统实现验证脚本
# 依赖: go 1.21+
# 用法: ./verify-deadman.sh [agent_dir]

set -e

AGENT_DIR="${1:-./rmdc-watchdog-agent}"

echo "=== 死手系统实现验证 ==="
echo "目标目录: $AGENT_DIR"
echo ""

# 检查目录
if [ ! -d "$AGENT_DIR" ]; then
    echo "⚠ 目录不存在: $AGENT_DIR"
    echo "尝试查找watchdog-agent目录..."
    AGENT_DIR=$(find . -type d -name "*watchdog*agent*" 2>/dev/null | head -1)
    if [ -z "$AGENT_DIR" ]; then
        echo "✗ 未找到agent目录"
        exit 1
    fi
    echo "找到: $AGENT_DIR"
fi

# 1. 验证心跳实现
echo ""
echo "[1/5] 验证心跳实现..."
if grep -rq "heartbeat\|Heartbeat" "$AGENT_DIR" --include="*.go" 2>/dev/null; then
    echo "✓ 找到心跳相关代码"
    HEARTBEAT_FILES=$(grep -rl "heartbeat\|Heartbeat" "$AGENT_DIR" --include="*.go" 2>/dev/null | head -3)
    echo "  文件: $HEARTBEAT_FILES"
else
    echo "⚠ 未找到心跳相关代码"
fi

# 2. 验证失败阈值
echo ""
echo "[2/5] 验证失败阈值 (maxRetryCount=12)..."
if grep -rq "12" "$AGENT_DIR" --include="*.go" 2>/dev/null | grep -qi "retry\|count\|max\|fail"; then
    echo "✓ 找到阈值配置"
else
    echo "⚠ 未明确找到阈值12的配置"
fi

# 3. 验证SIGTERM信号
echo ""
echo "[3/5] 验证终止信号 (SIGTERM)..."
if grep -rq "SIGTERM\|syscall.Signal" "$AGENT_DIR" --include="*.go" 2>/dev/null; then
    echo "✓ 找到SIGTERM信号使用"
else
    echo "⚠ 未找到SIGTERM信号"
fi

if grep -rq "SIGKILL" "$AGENT_DIR" --include="*.go" 2>/dev/null; then
    echo "⚠ 发现SIGKILL使用，请确认仅作为最后手段"
fi

# 4. 验证心跳间隔
echo ""
echo "[4/5] 验证心跳间隔..."
if grep -rq "2.*[Hh]our\|time.Hour.*2\|7200" "$AGENT_DIR" --include="*.go" 2>/dev/null; then
    echo "✓ 找到2小时间隔配置"
else
    echo "⚠ 未找到2小时成功间隔"
fi

if grep -rq "1.*[Hh]our\|time.Hour\|3600" "$AGENT_DIR" --include="*.go" 2>/dev/null; then
    echo "✓ 找到1小时间隔配置"
else
    echo "⚠ 未找到1小时失败间隔"
fi

# 5. 验证TOTP双向验证
echo ""
echo "[5/5] 验证TOTP双向验证..."
if grep -rq "SecondTOTPSecret\|second_totp_secret" "$AGENT_DIR" --include="*.go" 2>/dev/null; then
    echo "✓ 找到密钥获取逻辑"
else
    echo "⚠ 未找到密钥获取逻辑"
fi

if grep -rq "response.*[Tt]otp\|verify.*[Tt]otp" "$AGENT_DIR" --include="*.go" 2>/dev/null; then
    echo "✓ 找到响应TOTP验证"
else
    echo "⚠ 未找到响应TOTP验证，请确认双向验证"
fi

# 编译检查
echo ""
echo "[额外] 编译检查..."
cd "$AGENT_DIR"
if go build ./... 2>&1; then
    echo "✓ 编译通过"
else
    echo "⚠ 编译有问题"
fi

echo ""
echo "=== 验证完成 ==="
