#!/bin/bash
# Configure - Generate configuration files
# Run as appuser (mariano), no sudo required
#
# Usage:
#   ./configure.sh
#
# Generates:
#   - Nginx configs for core_room
#   - Validates .env files
#   - Outputs to .generated/ directory
#
# After running this, admin runs: sudo ./setup.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
GEN_DIR="$SCRIPT_DIR/.generated"
CORE_ROOM_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

echo "=== Core Room Configure ==="
echo ""
echo "This script generates configuration files for deployment."
echo "Run as appuser (no sudo required)."
echo ""

# Ensure we're NOT running as root
if [ "$EUID" -eq 0 ]; then
    echo "ERROR: Do not run this script with sudo"
    echo "Run as appuser instead: ./configure.sh"
    exit 1
fi

# =============================================================================
# 1. Create .generated directory
# =============================================================================
echo "Step 1: Preparing output directory..."
mkdir -p "$GEN_DIR"
echo "  Output directory: $GEN_DIR"

# =============================================================================
# 2. Load and validate environment
# =============================================================================
echo ""
echo "Step 2: Loading environment..."

# Load core_room/.env
if [ -f "$CORE_ROOM_ROOT/.env" ]; then
    set -a
    source "$CORE_ROOM_ROOT/.env"
    set +a
    echo "  Loaded: core_room/.env"
else
    echo "  ERROR: core_room/.env not found"
    exit 1
fi

# Validate required vars
REQUIRED_VARS="ROOM_NAME DEPLOYMENT_NAME NETWORK_NAME MANAGED_DOMAIN SOLEPRINT_DOMAIN"
MISSING=""
for var in $REQUIRED_VARS; do
    if [ -z "${!var}" ]; then
        MISSING="$MISSING $var"
    fi
done

if [ -n "$MISSING" ]; then
    echo "  ERROR: Missing required vars in core_room/.env:$MISSING"
    exit 1
fi

echo "  ROOM_NAME: $ROOM_NAME"
echo "  DEPLOYMENT_NAME: $DEPLOYMENT_NAME"
echo "  MANAGED_DOMAIN: $MANAGED_DOMAIN"
echo "  SOLEPRINT_DOMAIN: $SOLEPRINT_DOMAIN"

# =============================================================================
# 3. Check .env files for services
# =============================================================================
echo ""
echo "Step 3: Checking service .env files..."

for service in amar soleprint; do
    SERVICE_DIR="$CORE_ROOM_ROOT/$service"
    if [ ! -f "$SERVICE_DIR/.env" ]; then
        if [ -f "$SERVICE_DIR/.env.example" ]; then
            echo "  Creating $service/.env from example..."
            cp "$SERVICE_DIR/.env.example" "$SERVICE_DIR/.env"
            echo "  ⚠️  Edit $service/.env with production values before deployment"
        else
            echo "  ERROR: $service/.env.example not found"
            exit 1
        fi
    else
        echo "  ✓ $service/.env exists"
    fi
done

# =============================================================================
# 4. Generate Nginx configuration
# =============================================================================
echo ""
echo "Step 4: Generating nginx configuration..."

TEMPLATE="$SCRIPT_DIR/nginx/core_room.conf.template"
OUTPUT="$GEN_DIR/core_room.nginx.conf"

if [ ! -f "$TEMPLATE" ]; then
    echo "  ERROR: Template not found: $TEMPLATE"
    exit 1
fi

# Check for SSL certificates (just warn, don't fail)
SSL_CERT_AMAR="/etc/letsencrypt/live/room.mcrn.ar/fullchain.pem"
SSL_KEY_AMAR="/etc/letsencrypt/live/room.mcrn.ar/privkey.pem"
SSL_CERT_SOLEPRINT="/etc/letsencrypt/live/mcrn.ar/fullchain.pem"
SSL_KEY_SOLEPRINT="/etc/letsencrypt/live/mcrn.ar/privkey.pem"

echo "  Checking SSL certificates..."
for cert in "$SSL_CERT_AMAR" "$SSL_KEY_AMAR" "$SSL_CERT_SOLEPRINT" "$SSL_KEY_SOLEPRINT"; do
    if [ -f "$cert" ]; then
        echo "    ✓ $(basename $cert)"
    else
        echo "    ⚠️  Missing: $cert"
        echo "       Admin will need to generate SSL certificates"
    fi
done

# Generate nginx config from template
export ROOM_NAME DEPLOYMENT_NAME MANAGED_DOMAIN SOLEPRINT_DOMAIN
export SSL_CERT_AMAR SSL_KEY_AMAR SSL_CERT_SOLEPRINT SSL_KEY_SOLEPRINT

envsubst < "$TEMPLATE" > "$OUTPUT"

echo "  ✓ Generated: $OUTPUT"

# =============================================================================
# 5. Generate deployment summary
# =============================================================================
echo ""
echo "Step 5: Generating deployment summary..."

SUMMARY="$GEN_DIR/DEPLOYMENT.txt"

cat > "$SUMMARY" <<EOF
Core Room Deployment Configuration
Generated: $(date)
User: $USER
Host: $(hostname)

=== Environment ===
ROOM_NAME=$ROOM_NAME
DEPLOYMENT_NAME=$DEPLOYMENT_NAME
NETWORK_NAME=$NETWORK_NAME
MANAGED_DOMAIN=$MANAGED_DOMAIN
SOLEPRINT_DOMAIN=$SOLEPRINT_DOMAIN

=== Generated Files ===
- core_room.nginx.conf → /etc/nginx/sites-available/core_room.conf

=== Next Steps ===
1. Review generated files in: $GEN_DIR
2. Have admin run: sudo ./setup.sh
EOF

echo "  ✓ Generated: $SUMMARY"

# =============================================================================
# Done
# =============================================================================
echo ""
echo "=== Configuration Complete ==="
echo ""
echo "Generated files in: $GEN_DIR"
echo ""
echo "Next steps:"
echo "  1. Review generated nginx config:"
echo "     cat $OUTPUT"
echo ""
echo "  2. Have system admin run:"
echo "     sudo ./setup.sh"
echo ""
echo "  3. Or review deployment summary:"
echo "     cat $SUMMARY"
echo ""
