#!/bin/bash
# scripts/ci/security-scan.sh - Сканирование безопасности

set -e

echo "🔒 Running security scans..."

# Создание директории для отчетов
mkdir -p /tmp/security-reports

# 1. Сканирование зависимостей
echo "📦 Scanning dependencies for vulnerabilities..."

# Python зависимости
if [ -f "backend/requirements.txt" ]; then
    echo "  • Scanning Python dependencies..."
    docker run --rm -v "$(pwd)/backend:/app" -w /app python:3.11-slim bash -c "
        pip install safety bandit > /dev/null 2>&1
        echo 'Python Safety Report:' > /tmp/safety-report.txt
        safety check -r requirements.txt --output text >> /tmp/safety-report.txt 2>&1 || echo 'Safety scan completed with findings'
        cat /tmp/safety-report.txt
    " | tee /tmp/security-reports/python-dependencies.txt
fi

# Node.js зависимости
if [ -f "frontend/linktree-frontend/package.json" ]; then
    echo "  • Scanning Node.js dependencies..."
    docker run --rm -v "$(pwd)/frontend/linktree-frontend:/app" -w /app node:20-alpine sh -c "
        npm install --silent > /dev/null 2>&1
        npm audit --audit-level moderate 2>&1 || echo 'npm audit completed with findings'
    " | tee /tmp/security-reports/nodejs-dependencies.txt
fi

# 2. Сканирование кода на уязвимости
echo "🔍 Scanning source code for security issues..."

# Python код
if [ -d "backend" ]; then
    echo "  • Scanning Python code with Bandit..."
    docker run --rm -v "$(pwd)/backend:/app" -w /app python:3.11-slim bash -c "
        pip install bandit > /dev/null 2>&1
        bandit -r . -f txt 2>&1 || echo 'Bandit scan completed'
    " | tee /tmp/security-reports/python-code-scan.txt
fi

# 3. Сканирование Docker образов
echo "🐳 Scanning Docker images..."

# Получение списка образов проекта
images=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep -E "(catlink|links)" | head -5)

for image in $images; do
    echo "  • Scanning image: $image"
    
    # Используем простую проверку уязвимостей через docker history
    echo "    - Checking image layers..."
    docker history "$image" --no-trunc | head -10
    
    # Проверка на известные уязвимые базовые образы
    echo "    - Checking base image..."
    base_image=$(docker inspect "$image" | grep -o '"FROM [^"]*"' | head -1 || echo "unknown")
    echo "      Base image: $base_image"
    
done > /tmp/security-reports/docker-scan.txt

# 4. Сканирование конфигурации
echo "⚙️ Scanning configuration files..."

# Проверка .env файлов на потенциальные проблемы
echo "  • Checking environment configuration..."
if [ -f ".env" ]; then
    echo "    - Checking for hardcoded secrets in .env..."
    
    # Проверка на слабые пароли или ключи
    if grep -qi "password.*123\|secret.*test\|key.*test" .env; then
        echo "      ⚠️ Weak passwords or test keys found in .env"
    else
        echo "      ✅ No obvious weak credentials in .env"
    fi
    
    # Проверка на отладочный режим в продакшене
    if grep -q "DEBUG.*True" .env; then
        echo "      ⚠️ DEBUG mode is enabled"
    else
        echo "      ✅ DEBUG mode is properly configured"
    fi
fi

# Проверка Docker Compose на небезопасные настройки
echo "  • Checking Docker Compose security..."
if [ -f "docker-compose.yml" ]; then
    # Проверка на privileged режим
    if grep -q "privileged.*true" docker-compose.yml; then
        echo "      ⚠️ Privileged containers found"
    else
        echo "      ✅ No privileged containers"
    fi
    
    # Проверка на монтирование Docker socket
    if grep -q "/var/run/docker.sock" docker-compose.yml; then
        echo "      ⚠️ Docker socket is mounted (potential security risk)"
    else
        echo "      ✅ Docker socket is not exposed"
    fi
fi > /tmp/security-reports/config-scan.txt

# 5. Проверка сетевой безопасности
echo "🌐 Checking network security..."

# Проверка открытых портов
echo "  • Checking exposed ports..."
open_ports=$(docker-compose ps --services | xargs -I {} docker-compose port {} 2>/dev/null | grep -v "No container" || true)
if [ -n "$open_ports" ]; then
    echo "    Exposed ports:"
    echo "$open_ports"
else
    echo "    No exposed ports found"
fi > /tmp/security-reports/network-scan.txt

# 6. Проверка SSL/TLS конфигурации
echo "🔐 Checking SSL/TLS configuration..."

# Проверка наличия SSL настроек
if [ -f "nginx.conf" ] || [ -f "docker-compose.ssl.yml" ]; then
    echo "  • SSL configuration found"
    
    # Проверка на использование слабых протоколов
    if grep -r "ssl_protocols.*TLSv1[^.2]" . 2>/dev/null; then
        echo "    ⚠️ Weak TLS protocols detected"
    else
        echo "    ✅ TLS configuration appears secure"
    fi
else
    echo "  • No SSL configuration found (consider adding for production)"
fi >> /tmp/security-reports/ssl-scan.txt

# 7. Создание сводного отчета
echo "📊 Generating security summary..."

cat > /tmp/security-reports/security-summary.txt << EOF
CatLink Security Scan Summary
============================
Scan Date: $(date)
Commit: ${DRONE_COMMIT_SHA:-"local"}
Branch: ${DRONE_BRANCH:-"local"}

Scans Performed:
✓ Dependency vulnerability scan
✓ Source code security scan  
✓ Docker image security scan
✓ Configuration security check
✓ Network security assessment
✓ SSL/TLS configuration review

Reports Generated:
- python-dependencies.txt
- nodejs-dependencies.txt  
- python-code-scan.txt
- docker-scan.txt
- config-scan.txt
- network-scan.txt
- ssl-scan.txt

Recommendations:
1. Review dependency vulnerabilities and update packages
2. Address any code security issues found by static analysis
3. Keep Docker base images updated
4. Use strong passwords and secrets management
5. Enable SSL/TLS for production deployments
6. Regular security scans in CI/CD pipeline

For detailed findings, check individual report files.
EOF

# Подсчет найденных проблем
echo "📈 Security scan statistics..."
total_issues=0

# Подсчет проблем в зависимостях
if [ -f "/tmp/security-reports/python-dependencies.txt" ]; then
    python_issues=$(grep -c "vulnerability\|CRITICAL\|HIGH" /tmp/security-reports/python-dependencies.txt 2>/dev/null || echo "0")
    echo "  • Python dependency issues: $python_issues"
    total_issues=$((total_issues + python_issues))
fi

if [ -f "/tmp/security-reports/nodejs-dependencies.txt" ]; then
    node_issues=$(grep -c "vulnerability\|critical\|high" /tmp/security-reports/nodejs-dependencies.txt 2>/dev/null || echo "0")
    echo "  • Node.js dependency issues: $node_issues"
    total_issues=$((total_issues + node_issues))
fi

echo "  • Total security issues found: $total_issues"

# Вывод результатов
echo ""
echo "🔒 Security scan completed!"
echo "📁 Reports saved to /tmp/security-reports/"
echo ""
cat /tmp/security-reports/security-summary.txt

# Не фейлим build на проблемах безопасности, но выводим предупреждение
if [ "$total_issues" -gt 0 ]; then
    echo ""
    echo "⚠️ Security issues detected! Please review the reports."
    echo "   This is informational and does not fail the build."
fi

echo "✅ Security scan stage completed."