#!/bin/bash

# MAES Domain Setup Script
# One-command setup for custom domains with Let's Encrypt

set -e

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

# Banner
echo -e "${BLUE}"
echo "╔══════════════════════════════════════╗"
echo "║        MAES Domain Setup             ║"
echo "║  Custom Domain & Let's Encrypt       ║"
echo "╚══════════════════════════════════════╝"
echo -e "${NC}"

# Function to show usage
show_usage() {
    echo -e "${CYAN}Usage:${NC}"
    echo "  ./scripts/setup-domain.sh <domain> <email> [options]"
    echo ""
    echo -e "${CYAN}Arguments:${NC}"
    echo "  domain    Your domain name (e.g., maes.yourdomain.com)"
    echo "  email     Email for Let's Encrypt registration"
    echo ""
    echo -e "${CYAN}Options:${NC}"
    echo "  --staging       Use Let's Encrypt staging (for testing)"
    echo "  --no-ssl        Skip Let's Encrypt setup (self-signed only)"
    echo "  --localhost     Configure for localhost development"
    echo ""
    echo -e "${CYAN}Examples:${NC}"
    echo "  ./scripts/setup-domain.sh maes.example.com admin@example.com"
    echo "  ./scripts/setup-domain.sh maes.example.com admin@example.com --staging"
    echo "  ./scripts/setup-domain.sh localhost admin@example.com --localhost"
}

# Parse arguments
DOMAIN=""
EMAIL=""
USE_STAGING=false
USE_SSL=true
IS_LOCALHOST=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --staging)
            USE_STAGING=true
            shift
            ;;
        --no-ssl)
            USE_SSL=false
            shift
            ;;
        --localhost)
            IS_LOCALHOST=true
            DOMAIN="localhost"
            USE_SSL=false
            shift
            ;;
        --help|-h)
            show_usage
            exit 0
            ;;
        -*)
            echo -e "${RED}❌ Unknown option: $1${NC}"
            show_usage
            exit 1
            ;;
        *)
            if [ -z "$DOMAIN" ] && [ "$IS_LOCALHOST" = false ]; then
                DOMAIN="$1"
            elif [ -z "$EMAIL" ]; then
                EMAIL="$1"
            else
                echo -e "${RED}❌ Too many arguments${NC}"
                show_usage
                exit 1
            fi
            shift
            ;;
    esac
done

# Validation
if [ -z "$DOMAIN" ]; then
    echo -e "${RED}❌ Domain is required${NC}"
    show_usage
    exit 1
fi

if [ -z "$EMAIL" ] && [ "$USE_SSL" = true ]; then
    echo -e "${RED}❌ Email is required for Let's Encrypt${NC}"
    show_usage
    exit 1
fi

# Show configuration
echo -e "${GREEN}📋 Configuration:${NC}"
echo -e "   Domain: ${YELLOW}$DOMAIN${NC}"
echo -e "   Email: ${YELLOW}${EMAIL:-"N/A"}${NC}"
echo -e "   Let's Encrypt: ${YELLOW}$([ "$USE_SSL" = true ] && echo "Enabled" || echo "Disabled")${NC}"
echo -e "   Staging: ${YELLOW}$([ "$USE_STAGING" = true ] && echo "Yes" || echo "No")${NC}"
echo -e "   Localhost: ${YELLOW}$([ "$IS_LOCALHOST" = true ] && echo "Yes" || echo "No")${NC}"
echo ""

# Confirmation
if [ "$IS_LOCALHOST" = false ]; then
    echo -e "${YELLOW}⚠️  Prerequisites for custom domain:${NC}"
    echo "   1. Domain DNS must point to this server"
    echo "   2. Ports 80 and 443 must be open"
    echo "   3. No other web server should be running"
    echo ""
    read -p "Continue with setup? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 0
    fi
fi

# Create .env file
echo -e "${BLUE}🔧 Creating .env configuration...${NC}"

cat > .env << EOF
# MAES Platform Environment Configuration
# Generated by setup-domain.sh on $(date)

# ===========================================
# Domain & SSL Configuration
# ===========================================

DOMAIN=$DOMAIN
USE_LETS_ENCRYPT=$USE_SSL
EMAIL=$EMAIL
LETSENCRYPT_STAGING=$USE_STAGING

# ===========================================
# Application Configuration
# ===========================================

NODE_ENV=production
API_URL=https://$DOMAIN:3000

# ===========================================
# Database Configuration
# ===========================================

POSTGRES_PASSWORD=maes_secure_password_$(openssl rand -hex 8)
REDIS_PASSWORD=redis_secure_password_$(openssl rand -hex 8)

# ===========================================
# Security Configuration
# ===========================================

JWT_SECRET=$(openssl rand -base64 32)
SERVICE_AUTH_TOKEN=$(openssl rand -base64 32)
ENCRYPTION_KEY=$(openssl rand -base64 32 | cut -c1-32)

# ===========================================
# Feature Configuration
# ===========================================

SIEM_EXPORT_LIMIT=1000
SIEM_RATE_LIMIT=50
POWERSHELL_TIMEOUT=1800000
QUEUE_STALLED_INTERVAL=30000
QUEUE_MAX_STALLED_COUNT=1

# ===========================================
# CORS Configuration
# ===========================================

CORS_ORIGIN=
EOF

echo -e "${GREEN}✅ Environment configuration created${NC}"

# Stop any running services
echo -e "${BLUE}🛑 Stopping any running services...${NC}"
docker-compose down -v 2>/dev/null || true

# Build services
echo -e "${BLUE}🔨 Building Docker services...${NC}"
docker-compose build

if [ "$IS_LOCALHOST" = true ]; then
    # Localhost setup
    echo -e "${BLUE}🚀 Starting services for localhost...${NC}"
    docker-compose up -d
    
    echo ""
    echo -e "${GREEN}🎉 MAES is ready for localhost development!${NC}"
    echo -e "${GREEN}✅ Access your application at: https://localhost${NC}"
    echo -e "${YELLOW}   (Accept the self-signed certificate warning)${NC}"
    
elif [ "$USE_SSL" = true ]; then
    # Custom domain with Let's Encrypt
    echo -e "${BLUE}🔒 Setting up Let's Encrypt certificates...${NC}"
    chmod +x ssl/init-letsencrypt.sh
    ./ssl/init-letsencrypt.sh
    
    echo -e "${BLUE}🚀 Starting all services...${NC}"
    docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
    
    echo ""
    echo -e "${GREEN}🎉 MAES is ready with Let's Encrypt!${NC}"
    echo -e "${GREEN}✅ Access your application at: https://$DOMAIN${NC}"
    
else
    # Custom domain with self-signed certificate
    echo -e "${BLUE}🚀 Starting services with self-signed certificate...${NC}"
    docker-compose up -d
    
    echo ""
    echo -e "${GREEN}🎉 MAES is ready with self-signed certificate!${NC}"
    echo -e "${GREEN}✅ Access your application at: https://$DOMAIN${NC}"
    echo -e "${YELLOW}   (Accept the self-signed certificate warning)${NC}"
fi

# Show helpful commands
echo ""
echo -e "${CYAN}📋 Helpful commands:${NC}"
echo -e "   View logs: ${YELLOW}docker-compose logs -f${NC}"
echo -e "   Stop services: ${YELLOW}docker-compose down${NC}"
echo -e "   Restart: ${YELLOW}docker-compose restart${NC}"

if [ "$USE_SSL" = true ] && [ "$IS_LOCALHOST" = false ]; then
    echo -e "   Certificate logs: ${YELLOW}docker-compose logs -f certbot${NC}"
    echo -e "   Renew certificates: ${YELLOW}docker-compose exec certbot certbot renew${NC}"
fi

echo ""
echo -e "${GREEN}🚀 Setup complete! Welcome to MAES!${NC}"