#!/bin/bash
# Go 安全扫描脚本
# 使用 gosec 对代码进行安全扫描
#
# 使用方法:
#   ./scripts/security/run-gosec.sh           # 扫描所有代码
#   ./scripts/security/run-gosec.sh ./internal # 扫描指定目录
#
# 依赖:
#   go install github.com/securego/gosec/v2/cmd/gosec@latest

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

SCAN_DIR="${1:-./...}"
OUTPUT_FILE="gosec-report.json"

echo -e "${YELLOW}Running gosec security scan...${NC}"

# 检查 gosec 是否安装
if ! command -v gosec &> /dev/null; then
    echo -e "${RED}gosec not found. Installing...${NC}"
    go install github.com/securego/gosec/v2/cmd/gosec@latest
fi

# 运行 gosec
gosec -fmt json -out="${OUTPUT_FILE}" "${SCAN_DIR}"

# 检查返回码
RESULT=$?

if [ $RESULT -eq 0 ]; then
    echo -e "${GREEN}No issues found!${NC}"
else
    echo -e "${RED}Security issues detected!${NC}"
    echo -e "${YELLOW}Report saved to: ${OUTPUT_FILE}${NC}"
fi

exit $RESULT
