#!/bin/bash
# Setup script for CVE Dashboard environment configuration
# Creates .env files from .env.example templates with proper IP configuration

set -e

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

echo "CVE Dashboard Environment Setup"
echo "================================"
echo ""

# Detect current IP address
DETECTED_IP=$(hostname -I | awk '{print $1}')

# Prompt for IP address
read -p "Enter server IP address [$DETECTED_IP]: " INPUT_IP
SERVER_IP="${INPUT_IP:-$DETECTED_IP}"

if [ -z "$SERVER_IP" ]; then
    echo "ERROR: No IP address provided and auto-detection failed."
    exit 1
fi

echo ""
echo "Using IP: $SERVER_IP"
echo ""

# Setup backend .env
BACKEND_ENV="$PROJECT_ROOT/backend/.env"
if [ -f "$BACKEND_ENV" ]; then
    read -p "backend/.env exists. Overwrite? [y/N]: " OVERWRITE
    if [[ ! "$OVERWRITE" =~ ^[Yy]$ ]]; then
        echo "Skipping backend/.env"
    else
        cat > "$BACKEND_ENV" << ENVFILE
# Backend Configuration
PORT=3001
API_HOST=$SERVER_IP
CORS_ORIGINS=http://$SERVER_IP:3000
ENVFILE
        echo "Created backend/.env"
    fi
else
    cat > "$BACKEND_ENV" << ENVFILE
# Backend Configuration
PORT=3001
API_HOST=$SERVER_IP
CORS_ORIGINS=http://$SERVER_IP:3000
ENVFILE
    echo "Created backend/.env"
fi

# Setup frontend .env
FRONTEND_ENV="$PROJECT_ROOT/frontend/.env"
if [ -f "$FRONTEND_ENV" ]; then
    read -p "frontend/.env exists. Overwrite? [y/N]: " OVERWRITE
    if [[ ! "$OVERWRITE" =~ ^[Yy]$ ]]; then
        echo "Skipping frontend/.env"
    else
        cat > "$FRONTEND_ENV" << ENVFILE
# Frontend Configuration
# API_BASE should include the /api path
REACT_APP_API_BASE=http://$SERVER_IP:3001/api
# API_HOST is used for direct file URLs (no /api)
REACT_APP_API_HOST=http://$SERVER_IP:3001
ENVFILE
        echo "Created frontend/.env"
    fi
else
    cat > "$FRONTEND_ENV" << ENVFILE
# Frontend Configuration
# API_BASE should include the /api path
REACT_APP_API_BASE=http://$SERVER_IP:3001/api
# API_HOST is used for direct file URLs (no /api)
REACT_APP_API_HOST=http://$SERVER_IP:3001
ENVFILE
    echo "Created frontend/.env"
fi

echo ""
echo "Setup complete!"
echo ""
echo "Next steps:"
echo "  1. If servers are running, restart them to apply changes"
echo "  2. Run: ./start-servers.sh"
echo ""
