#!/bin/bash
# Security scanning automation script
# Runs SAST, DAST, dependency scanning, and container scanning

set -e

echo "🔒 Starting security scanning..."

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# SAST - Static Application Security Testing
echo -e "${YELLOW}Running SAST (Static Analysis)...${NC}"
if command -v semgrep &> /dev/null; then
  semgrep --config=auto --json -o sast-results.json . || true
  echo -e "${GREEN}✓ SAST complete${NC}"
else
  echo -e "${RED}✗ Semgrep not installed. Install with: pip install semgrep${NC}"
fi

# Dependency Scanning
echo -e "${YELLOW}Running dependency vulnerability scan...${NC}"
pnpm audit --audit-level moderate --json > dependency-scan.json || true
echo -e "${GREEN}✓ Dependency scan complete${NC}"

# Container Scanning
echo -e "${YELLOW}Running container image scanning...${NC}"
if command -v trivy &> /dev/null; then
  for dockerfile in $(find . -name "Dockerfile"); do
    echo "Scanning $dockerfile..."
    trivy fs --security-checks vuln,config --format json -o "container-scan-$(basename $(dirname $dockerfile)).json" "$(dirname $dockerfile)" || true
  done
  echo -e "${GREEN}✓ Container scan complete${NC}"
else
  echo -e "${RED}✗ Trivy not installed. Install from: https://github.com/aquasecurity/trivy${NC}"
fi

# Generate summary
echo -e "${YELLOW}Generating security scan summary...${NC}"
cat > security-scan-summary.md << EOF
# Security Scan Summary

**Date**: $(date -u +"%Y-%m-%d %H:%M:%S UTC")

## SAST Results
- Report: sast-results.json
- Status: See report for details

## Dependency Scan
- Report: dependency-scan.json
- Status: See report for details

## Container Scan
- Reports: container-scan-*.json
- Status: See reports for details

## Recommendations
1. Review all findings
2. Fix high and critical vulnerabilities immediately
3. Address medium vulnerabilities in next sprint
4. Document accepted risks for low vulnerabilities

EOF

echo -e "${GREEN}✅ Security scanning complete!${NC}"
echo "Reports generated in current directory"

