#!/bin/bash

# 安全性檢查腳本
echo "🔒 專案安全性檢查開始..."
echo "====================================="

# 檢查敏感資訊洩露
echo "🕵️ 1. 敏感資訊洩露檢查"
echo "-------------------------------------"

# 定義敏感關鍵詞
sensitive_patterns=(
    "password"
    "api[_-]?key"
    "secret"
    "token"
    "private[_-]?key"
    "access[_-]?key"
    "client[_-]?secret"
    "database[_-]?url"
    "connection[_-]?string"
)

found_issues=0

for pattern in "${sensitive_patterns[@]}"; do
    echo "檢查模式: $pattern"
    matches=$(find . -name "*.md" -o -name "*.json" -o -name "*.sh" | xargs grep -il "$pattern" 2>/dev/null | grep -v ".git" | head -5)
    if [ -n "$matches" ]; then
        echo "⚠️ 發現可能的敏感資訊:"
        echo "$matches" | while read -r file; do
            echo "   $file"
            grep -in "$pattern" "$file" | head -2 | sed 's/^/      /'
        done
        found_issues=$((found_issues + 1))
    else
        echo "✅ 未發現 $pattern 相關資訊"
    fi
    echo ""
done

# 檢查硬編碼配置
echo "⚙️ 2. 硬編碼配置檢查"
echo "-------------------------------------"

config_patterns=(
    "localhost"
    "127\.0\.0\.1"
    "192\.168\."
    "\.env"
    "config\.json"
    "development"
    "staging"
    "production"
)

for pattern in "${config_patterns[@]}"; do
    matches=$(find docs/ -name "*.md" -o -name "*.json" | xargs grep -l "$pattern" 2>/dev/null)
    if [ -n "$matches" ]; then
        echo "📍 發現配置相關資訊 ($pattern):"
        echo "$matches" | sed 's/^/   /'
    fi
done
echo ""

# 檢查權限和存取控制
echo "🛡️ 3. 權限設計檢查"
echo "-------------------------------------"

# 檢查是否有權限相關文檔
permission_files=(
    "docs/04_technical/api-specifications.md"
    "docs/02_design/business-logic-rules.md"
    "docs/01_requirement/system_structure_design.json"
)

for file in "${permission_files[@]}"; do
    if [ -f "$file" ]; then
        # 檢查權限相關關鍵詞
        auth_keywords=$(grep -ic "auth\|permission\|role\|access\|jwt\|token" "$file" 2>/dev/null || echo 0)
        if [ "$auth_keywords" -gt 0 ]; then
            echo "✅ $file: 包含 $auth_keywords 個權限相關設計"
        else
            echo "⚠️ $file: 缺少權限設計說明"
        fi
    else
        echo "❌ $file: 檔案不存在"
    fi
done
echo ""

# 檢查資料加密設計
echo "🔐 4. 資料加密設計檢查"
echo "-------------------------------------"

encryption_keywords=(
    "encrypt"
    "decrypt" 
    "hash"
    "bcrypt"
    "ssl"
    "tls"
    "https"
)

total_encryption_refs=0
for keyword in "${encryption_keywords[@]}"; do
    refs=$(find docs/ -name "*.md" | xargs grep -ic "$keyword" 2>/dev/null | awk '{sum+=$1} END {print sum+0}')
    total_encryption_refs=$((total_encryption_refs + refs))
done

if [ "$total_encryption_refs" -gt 0 ]; then
    echo "✅ 發現 $total_encryption_refs 個加密相關設計"
else
    echo "⚠️ 缺少資料加密設計說明"
fi
echo ""

# 檢查第三方整合安全性
echo "🔌 5. 第三方整合安全性檢查"
echo "-------------------------------------"

if [ -f "docs/04_technical/third-party-integration-specification.md" ]; then
    # 檢查第三方服務的安全考量
    security_mentions=$(grep -ic "security\|secure\|auth\|key\|token\|ssl" "docs/04_technical/third-party-integration-specification.md" 2>/dev/null || echo 0)
    
    if [ "$security_mentions" -gt 5 ]; then
        echo "✅ 第三方整合包含充足的安全考量 ($security_mentions 處)"
    elif [ "$security_mentions" -gt 0 ]; then
        echo "⚠️ 第三方整合安全考量不足 ($security_mentions 處)"
    else
        echo "❌ 第三方整合缺少安全考量"
    fi
else
    echo "❌ 第三方整合規格文檔不存在"
fi
echo ""

# 檢查檔案權限
echo "📂 6. 檔案權限檢查"
echo "-------------------------------------"

# 檢查腳本檔案權限
find . -name "*.sh" -type f | while read -r script; do
    if [ -x "$script" ]; then
        echo "✅ $script: 具有執行權限"
    else
        echo "⚠️ $script: 缺少執行權限"
    fi
done

# 檢查是否有過於寬鬆的權限
find . -type f -perm 777 2>/dev/null | while read -r file; do
    echo "❌ $file: 權限過於寬鬆 (777)"
done
echo ""

# 檢查Git忽略設定
echo "📋 7. Git安全設定檢查"  
echo "-------------------------------------"

if [ -f ".gitignore" ]; then
    # 檢查是否忽略了敏感檔案
    sensitive_extensions=(
        "\.env"
        "\.key"
        "\.pem"
        "config\.json"
        "secrets"
        "\.log"
    )
    
    gitignore_score=0
    for ext in "${sensitive_extensions[@]}"; do
        if grep -q "$ext" .gitignore 2>/dev/null; then
            echo "✅ .gitignore 包含 $ext"
            gitignore_score=$((gitignore_score + 1))
        else
            echo "⚠️ .gitignore 缺少 $ext"
        fi
    done
    
    echo "Git安全設定評分: $gitignore_score/${#sensitive_extensions[@]}"
else
    echo "❌ .gitignore 檔案不存在"
fi
echo ""

# 生成安全性總結報告
echo "📊 安全性檢查總結"
echo "====================================="

# 計算安全性分數
security_score=0
max_score=7

# 評分邏輯
if [ $found_issues -eq 0 ]; then
    security_score=$((security_score + 2))
    echo "✅ 敏感資訊檢查: 通過 (+2分)"
else
    echo "❌ 敏感資訊檢查: 發現 $found_issues 個問題"
fi

if [ "$total_encryption_refs" -gt 0 ]; then
    security_score=$((security_score + 1))
    echo "✅ 加密設計: 通過 (+1分)"
else
    echo "❌ 加密設計: 不足"
fi

if [ -f "docs/04_technical/third-party-integration-specification.md" ] && [ "$security_mentions" -gt 5 ]; then
    security_score=$((security_score + 1))
    echo "✅ 第三方整合安全: 通過 (+1分)"
else
    echo "❌ 第三方整合安全: 不足"
fi

if [ -f ".gitignore" ] && [ "$gitignore_score" -gt 3 ]; then
    security_score=$((security_score + 1))
    echo "✅ Git安全設定: 通過 (+1分)"
else
    echo "❌ Git安全設定: 不足"
fi

# 其他檢查項目簡化評分
security_score=$((security_score + 2)) # 權限檢查和配置檢查的基礎分數

final_score=$(echo "scale=1; $security_score * 10 / $max_score" | bc -l 2>/dev/null || echo "0")

echo ""
echo "🏆 總體安全性評分: $final_score/10"

if (( $(echo "$final_score >= 8" | bc -l 2>/dev/null || echo 0) )); then
    echo "🎉 安全性評級: 優秀"
elif (( $(echo "$final_score >= 6" | bc -l 2>/dev/null || echo 0) )); then
    echo "👍 安全性評級: 良好" 
elif (( $(echo "$final_score >= 4" | bc -l 2>/dev/null || echo 0) )); then
    echo "⚠️ 安全性評級: 尚可"
else
    echo "❌ 安全性評級: 需要改進"
fi

echo ""
echo "建議改進項目:"
if [ $found_issues -gt 0 ]; then
    echo "- 移除或保護敏感資訊"
fi
if [ "$total_encryption_refs" -eq 0 ]; then
    echo "- 補充資料加密設計"
fi
if [ ! -f ".gitignore" ] || [ "$gitignore_score" -le 3 ]; then
    echo "- 完善Git安全設定"
fi

echo "檢查完成時間: $(date)"