#!/bin/bash

# Secret scanning script for DevOps dashboard
# Scans for common secret patterns in the codebase

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

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

# Secret patterns to scan for
declare -a PATTERNS=(
  "password\s*=\s*['\"][^'\"]+['\"]"
  "api_key\s*=\s*['\"][^'\"]+['\"]"
  "secret\s*=\s*['\"][^'\"]+['\"]"
  "token\s*=\s*['\"][^'\"]+['\"]"
  "private_key\s*=\s*['\"][^'\"]+['\"]"
  "aws_access_key_id\s*=\s*['\"][^'\"]+['\"]"
  "aws_secret_access_key\s*=\s*['\"][^'\"]+['\"]"
  "connection_string\s*=\s*['\"][^'\"]+['\"]"
  "mongodb://[^'\"]+"
  "mysql://[^'\"]+"
  "postgresql://[^'\"]+"
  "sk-[a-zA-Z0-9]{32,}"  # Stripe keys
  "AIza[0-9A-Za-z\-_]{35}"  # Google API keys
  "AKIA[0-9A-Z]{16}"  # AWS access key
)

# Files to exclude
declare -a EXCLUDE_PATTERNS=(
  "node_modules"
  ".git"
  "dist"
  "build"
  ".next"
  "coverage"
  "*.min.js"
  "*.min.css"
  "package-lock.json"
  "pnpm-lock.yaml"
  "yarn.lock"
)

found_secrets=0

echo -e "${GREEN}Scanning for secrets in $REPO_ROOT${NC}"
echo ""

# Build exclude arguments for grep
exclude_args=""
for pattern in "${EXCLUDE_PATTERNS[@]}"; do
  exclude_args="$exclude_args --exclude=$pattern"
done

# Scan for each pattern
for pattern in "${PATTERNS[@]}"; do
  echo -e "${YELLOW}Scanning for pattern: $pattern${NC}"

  if grep -r "$pattern" "$REPO_ROOT" "$exclude_args" --include="*.js" --include="*.ts" --include="*.tsx" --include="*.jsx" --include="*.json" --include="*.env*" 2>/dev/null | grep -v "example" | grep -v "placeholder" | grep -v "your-"; then
    echo -e "${RED}⚠️  Potential secrets found matching: $pattern${NC}"
    grep -r "$pattern" "$REPO_ROOT" "$exclude_args" --include="*.js" --include="*.ts" --include="*.tsx" --include="*.jsx" --include="*.json" --include="*.env*" 2>/dev/null | grep -v "example" | grep -v "placeholder" | grep -v "your-"
    found_secrets=1
  fi
done

echo ""
if [ $found_secrets -eq 0 ]; then
  echo -e "${GREEN}✓ No secrets found${NC}"
  exit 0
else
  echo -e "${RED}✗ Potential secrets detected! Please review and remove them before committing.${NC}"
  exit 1
fi
