#!/bin/bash
# =============================================================================
# MockupAWS Secrets Setup Script
# =============================================================================
# This script generates secure secrets for production deployment
# Run this script to create a secure .env file
#
# Usage:
#   chmod +x scripts/setup-secrets.sh
#   ./scripts/setup-secrets.sh
#
# Or specify output file:
#   ./scripts/setup-secrets.sh /path/to/.env
# =============================================================================

set -e

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

# Output file
OUTPUT_FILE="${1:-.env}"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  MockupAWS Secrets Generator${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Check if output file already exists
if [ -f "$OUTPUT_FILE" ]; then
    echo -e "${YELLOW}⚠️  Warning: $OUTPUT_FILE already exists${NC}"
    read -p "Do you want to overwrite it? (y/N): " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}Aborted. No changes made.${NC}"
        exit 0
    fi
fi

echo -e "${BLUE}Generating secure secrets...${NC}"
echo ""

# Generate JWT Secret (256 bits = 64 hex chars)
JWT_SECRET=$(openssl rand -hex 32)
echo -e "${GREEN}✓${NC} JWT Secret generated (64 hex characters)"

# Generate API Key Encryption Key
API_KEY_ENCRYPTION=$(openssl rand -hex 16)
echo -e "${GREEN}✓${NC} API Key encryption key generated"

# Generate Database password
DB_PASSWORD=$(openssl rand -base64 24 | tr -d "=+/" | cut -c1-20)
echo -e "${GREEN}✓${NC} Database password generated"

# Generate SendGrid-like API key placeholder
SENDGRID_API_KEY="sg_$(openssl rand -hex 24)"
echo -e "${GREEN}✓${NC} Example SendGrid API key generated"

echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Creating $OUTPUT_FILE${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Write the .env file
cat > "$OUTPUT_FILE" << EOF
# =============================================================================
# MockupAWS Environment Configuration
# Generated on: $(date '+%Y-%m-%d %H:%M:%S')
# =============================================================================

# =============================================================================
# Database
# =============================================================================
DATABASE_URL=postgresql+asyncpg://postgres:${DB_PASSWORD}@localhost:5432/mockupaws

# =============================================================================
# Application
# =============================================================================
APP_NAME=mockupAWS
DEBUG=false
API_V1_STR=/api/v1

# =============================================================================
# JWT Authentication
# =============================================================================
JWT_SECRET_KEY=${JWT_SECRET}
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
REFRESH_TOKEN_EXPIRE_DAYS=7

# =============================================================================
# Security
# =============================================================================
BCRYPT_ROUNDS=12
API_KEY_PREFIX=mk_

# =============================================================================
# Email Configuration
# =============================================================================
# Provider: sendgrid or ses
EMAIL_PROVIDER=sendgrid
EMAIL_FROM=noreply@mockupaws.com

# SendGrid Configuration
# Replace with your actual API key from sendgrid.com
SENDGRID_API_KEY=${SENDGRID_API_KEY}

# AWS SES Configuration (alternative)
# AWS_ACCESS_KEY_ID=AKIA...
# AWS_SECRET_ACCESS_KEY=...
# AWS_REGION=us-east-1

# =============================================================================
# Reports & Storage
# =============================================================================
REPORTS_STORAGE_PATH=./storage/reports
REPORTS_MAX_FILE_SIZE_MB=50
REPORTS_CLEANUP_DAYS=30
REPORTS_RATE_LIMIT_PER_MINUTE=10

# =============================================================================
# Scheduler
# =============================================================================
SCHEDULER_ENABLED=true
SCHEDULER_INTERVAL_MINUTES=5

# =============================================================================
# Frontend
# =============================================================================
FRONTEND_URL=http://localhost:5173
ALLOWED_HOSTS=localhost,127.0.0.1
EOF

echo -e "${GREEN}✓${NC} Environment file created: $OUTPUT_FILE"
echo ""
echo -e "${YELLOW}⚠️  IMPORTANT NEXT STEPS:${NC}"
echo ""
echo -e "1. ${BLUE}Update email configuration:${NC}"
echo "   - Sign up at https://sendgrid.com (free tier: 100 emails/day)"
echo "   - Generate an API key and replace SENDGRID_API_KEY"
echo ""
echo -e "2. ${BLUE}Verify your sender domain:${NC}"
echo "   - In SendGrid: https://app.sendgrid.com/settings/sender_auth"
echo ""
echo -e "3. ${Blue}Update database password${NC}"
echo "   - Change the postgres password in your database"
echo ""
echo -e "4. ${BLUE}Secure your secrets:${NC}"
echo "   - NEVER commit .env to git"
echo "   - Add .env to .gitignore if not already present"
echo "   - Use a secrets manager in production"
echo ""
echo -e "${GREEN}✓ Setup complete!${NC}"
echo ""

# Display generated secrets (for reference)
echo -e "${BLUE}Generated Secrets (save these securely):${NC}"
echo -e "  JWT_SECRET_KEY: ${JWT_SECRET:0:20}..."
echo -e "  DB_PASSWORD: ${DB_PASSWORD:0:10}..."
echo ""

# Verify .gitignore
echo -e "${BLUE}Checking .gitignore...${NC}"
if [ -f ".gitignore" ]; then
    if grep -q "^\.env$" .gitignore || grep -q "\.env" .gitignore; then
        echo -e "${GREEN}✓ .env is already in .gitignore${NC}"
    else
        echo -e "${YELLOW}⚠️  Warning: .env is NOT in .gitignore${NC}"
        read -p "Add .env to .gitignore? (Y/n): " -n 1 -r
        echo ""
        if [[ ! $REPLY =~ ^[Nn]$ ]]; then
            echo ".env" >> .gitignore
            echo -e "${GREEN}✓ Added .env to .gitignore${NC}"
        fi
    fi
else
    echo -e "${YELLOW}⚠️  No .gitignore file found${NC}"
fi

echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}  Secrets generated successfully!${NC}"
echo -e "${BLUE}========================================${NC}"
