#!/bin/bash

# Quick fix for missing environment file

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${BLUE}[INFO]${NC} Creating missing environment configuration..."

# Check if environment file exists
if [ ! -f /etc/airwavepbx/airwavepbx.env ]; then
    echo -e "${BLUE}[INFO]${NC} Creating environment configuration..."
    
    # Get domain from user
    read -p "Enter your domain name (e.g., pbx.example.com): " DOMAIN
    read -p "Enter admin email: " ADMIN_EMAIL
    
    # Create config directory
    sudo mkdir -p /etc/airwavepbx
    
    # Get AMI password from Asterisk config if it exists
    AMI_PASSWORD="changeme"
    if [ -f /etc/airwavepbx/asterisk-credentials.txt ]; then
        source /etc/airwavepbx/asterisk-credentials.txt
    fi
    
    # Create environment file
    sudo tee /etc/airwavepbx/airwavepbx.env > /dev/null << EOF
# AirwavePBX Configuration
NODE_ENV=production
PORT=3000
API_PORT=3001

# Domain
DOMAIN=$DOMAIN
ADMIN_EMAIL=$ADMIN_EMAIL

# Security
JWT_SECRET=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
SESSION_SECRET=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)

# Asterisk
AMI_PASSWORD=$AMI_PASSWORD

# Database
DATABASE_PATH=/var/lib/airwavepbx/data/airwavepbx.db
EOF
    
    echo -e "${GREEN}[SUCCESS]${NC} Environment file created"
else
    # Load existing environment
    source /etc/airwavepbx/airwavepbx.env
    echo -e "${GREEN}[SUCCESS]${NC} Using existing environment configuration"
fi

# Fix Nginx configuration
echo -e "${BLUE}[INFO]${NC} Fixing Nginx configuration..."

# Load environment variables
source /etc/airwavepbx/airwavepbx.env

# Remove broken config
sudo rm -f /etc/nginx/sites-enabled/airwavepbx
sudo rm -f /etc/nginx/sites-available/airwavepbx

# Create proper Nginx config
sudo tee /etc/nginx/sites-available/airwavepbx > /dev/null << NGINX_EOF
server {
    listen 80;
    server_name $DOMAIN;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    location /api/ {
        proxy_pass http://localhost:3001/api/;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    location /ws {
        proxy_pass http://localhost:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
}
NGINX_EOF

# Enable site
sudo ln -sf /etc/nginx/sites-available/airwavepbx /etc/nginx/sites-enabled/

# Test and reload Nginx
if sudo nginx -t; then
    sudo systemctl reload nginx
    echo -e "${GREEN}[SUCCESS]${NC} Nginx configured successfully"
else
    echo -e "${RED}[ERROR]${NC} Nginx configuration failed"
fi

# Create database directory if missing
sudo mkdir -p /var/lib/airwavepbx/data
sudo chown -R airwavepbx:airwavepbx /var/lib/airwavepbx 2>/dev/null || true

# Restart services to pick up environment
echo -e "${BLUE}[INFO]${NC} Restarting services with new configuration..."
pm2 restart all

# Wait for services
sleep 5

# Check service status
echo -e "${BLUE}[INFO]${NC} Checking service status..."
pm2 status

# Final instructions
echo
echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}Configuration Fixed!${NC}"
echo -e "${GREEN}=========================================${NC}"
echo
echo "Access your PBX at: http://$DOMAIN"
echo "Username: admin"
echo "Password: admin"
echo
echo "If you can't access the web interface:"
echo "1. Check DNS points to this server"
echo "2. Check firewall: sudo ufw status"
echo "3. Allow HTTP: sudo ufw allow 80/tcp"
echo "4. Allow HTTPS: sudo ufw allow 443/tcp"