#!/bin/bash
# verify-watchdog.sh - Watchdog模块验证脚本
# 依赖: go 1.21+, golangci-lint (可选)
# 用法: ./verify-watchdog.sh [watchdog_dir]

set -e

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

echo "=== Watchdog 模块验证 ==="
echo "目标目录: $WATCHDOG_DIR"
echo ""

# 检查目录存在
if [ ! -d "$WATCHDOG_DIR" ]; then
    echo "错误: 目录不存在 $WATCHDOG_DIR"
    exit 1
fi

# 1. 编译检查
echo "[1/5] 编译检查..."
cd "$WATCHDOG_DIR"
if go build ./... 2>&1; then
    echo "✓ 编译通过"
else
    echo "✗ 编译失败"
    exit 1
fi

# 2. 单元测试
echo ""
echo "[2/5] 单元测试..."
if go test ./internal/... -v -cover 2>&1; then
    echo "✓ 单元测试通过"
else
    echo "⚠ 部分测试失败，请检查"
fi

# 3. Lint检查
echo ""
echo "[3/5] Lint检查..."
if command -v golangci-lint &> /dev/null; then
    if golangci-lint run ./... 2>&1; then
        echo "✓ Lint检查通过"
    else
        echo "⚠ Lint检查有警告"
    fi
else
    echo "⚠ golangci-lint未安装，跳过"
fi

# 4. TOTP参数验证
echo ""
echo "[4/5] TOTP参数验证..."

# Tier-One: 8位/30分钟
if grep -rq "Digits.*8" pkg/totp/ 2>/dev/null || grep -rq "8.*Digits" pkg/totp/ 2>/dev/null; then
    echo "✓ Tier-One TOTP位数配置存在"
else
    echo "⚠ 未找到Tier-One TOTP位数定义 (应为8位)"
fi

# Tier-Two: 6位/30秒
if grep -rq "Digits.*6" pkg/totp/ 2>/dev/null || grep -rq "6.*Digits" pkg/totp/ 2>/dev/null; then
    echo "✓ Tier-Two TOTP位数配置存在"
else
    echo "⚠ 未找到Tier-Two TOTP位数定义 (应为6位)"
fi

# 5. K8S操作白名单验证
echo ""
echo "[5/5] K8S操作白名单验证..."
ALLOWED_ACTIONS="logs exec scale restart delete get apply"
K8S_SERVICE="internal/service/k8s_service.go"

if [ -f "$K8S_SERVICE" ]; then
    for action in $ALLOWED_ACTIONS; do
        if grep -q "case \"$action\"" "$K8S_SERVICE" 2>/dev/null; then
            echo "✓ K8S操作 '$action' 已实现"
        else
            echo "⚠ K8S操作 '$action' 未找到"
        fi
    done
else
    echo "⚠ K8S服务文件不存在: $K8S_SERVICE"
fi

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