#!/bin/bash

# SSL Fix with proper certificate checking

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

echo "========================================="
echo "AirwavePBX SSL Configuration"
echo "========================================="
echo

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

# First, let's check if services are actually running
echo -e "${BLUE}[INFO]${NC} Checking service status..."
echo

# Check if port 3000 is listening
if netstat -tuln | grep -q ":3000 "; then
    echo -e "${GREEN}[OK]${NC} Frontend is listening on port 3000"
else
    echo -e "${RED}[ERROR]${NC} Frontend not listening on port 3000"
    echo "Checking PM2 logs..."
    pm2 logs --lines 20 --nostream
fi

# Check if port 3001 is listening
if netstat -tuln | grep -q ":3001 "; then
    echo -e "${GREEN}[OK]${NC} API is listening on port 3001"
else
    echo -e "${RED}[ERROR]${NC} API not listening on port 3001"
fi

# Test local connectivity
echo
echo -e "${BLUE}[INFO]${NC} Testing local connectivity..."
if curl -s -o /dev/null -w "%{http_code}" http://localhost:3000 | grep -q "200\|302"; then
    echo -e "${GREEN}[OK]${NC} Frontend responding locally"
else
    echo -e "${RED}[ERROR]${NC} Frontend not responding locally"
fi

# Check existing certificates
echo
echo -e "${BLUE}[INFO]${NC} Checking for existing SSL certificates..."

CERT_EXISTS=false
if [ -d "/etc/letsencrypt/live/$DOMAIN" ]; then
    echo -e "${GREEN}[FOUND]${NC} Existing certificate for $DOMAIN"
    # Check certificate validity
    if openssl x509 -checkend 86400 -noout -in "/etc/letsencrypt/live/$DOMAIN/cert.pem" 2>/dev/null; then
        echo -e "${GREEN}[OK]${NC} Certificate is valid"
        CERT_EXISTS=true
    else
        echo -e "${YELLOW}[WARNING]${NC} Certificate exists but may be expired"
    fi
fi

# Configure SSL
if [ "$CERT_EXISTS" = true ]; then
    echo
    echo -e "${BLUE}[INFO]${NC} Using existing SSL certificate..."
    
    # Create SSL-enabled Nginx config
    sudo tee /etc/nginx/sites-available/airwavepbx-ssl > /dev/null << NGINX_SSL
server {
    listen 80;
    server_name $DOMAIN;
    return 301 https://\$server_name\$request_uri;
}

server {
    listen 443 ssl http2;
    server_name $DOMAIN;

    ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    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_SSL

    # Enable SSL config
    sudo ln -sf /etc/nginx/sites-available/airwavepbx-ssl /etc/nginx/sites-enabled/airwavepbx
    
else
    echo
    echo -e "${BLUE}[INFO]${NC} No existing SSL certificate found"
    echo
    echo "Options:"
    echo "1. Setup new Let's Encrypt certificate (recommended)"
    echo "2. Continue with HTTP only"
    echo
    read -p "Choose option (1-2): " SSL_CHOICE
    
    if [ "$SSL_CHOICE" = "1" ]; then
        # First check DNS
        echo
        echo -e "${BLUE}[INFO]${NC} Checking DNS for $DOMAIN..."
        SERVER_IP=$(curl -s http://ipinfo.io/ip)
        DNS_IP=$(dig +short $DOMAIN | tail -n1)
        
        if [ "$SERVER_IP" = "$DNS_IP" ]; then
            echo -e "${GREEN}[OK]${NC} DNS is properly configured"
            echo "Server IP: $SERVER_IP"
            echo "DNS points to: $DNS_IP"
            
            # Install certbot if needed
            if ! command -v certbot &> /dev/null; then
                echo -e "${BLUE}[INFO]${NC} Installing certbot..."
                sudo apt-get update
                sudo apt-get install -y certbot python3-certbot-nginx
            fi
            
            # Get certificate
            echo -e "${BLUE}[INFO]${NC} Obtaining SSL certificate..."
            sudo certbot --nginx -d $DOMAIN --non-interactive --agree-tos -m $ADMIN_EMAIL --redirect
            
        else
            echo -e "${RED}[ERROR]${NC} DNS not properly configured!"
            echo "Server IP: $SERVER_IP"
            echo "DNS points to: $DNS_IP"
            echo
            echo "Please update your DNS A record to point to $SERVER_IP"
            echo "Then run this script again."
        fi
    fi
fi

# Test and reload Nginx
echo
echo -e "${BLUE}[INFO]${NC} Testing Nginx configuration..."
if sudo nginx -t; then
    sudo systemctl reload nginx
    echo -e "${GREEN}[OK]${NC} Nginx reloaded successfully"
else
    echo -e "${RED}[ERROR]${NC} Nginx configuration error"
fi

# Final status check
echo
echo "========================================="
echo "Status Check Complete"
echo "========================================="
echo
if [ "$CERT_EXISTS" = true ] || [ "$SSL_CHOICE" = "1" ]; then
    echo "Access your PBX at: https://$DOMAIN"
else
    echo "Access your PBX at: http://$DOMAIN"
fi
echo
echo "Troubleshooting commands:"
echo "  pm2 logs                    # View application logs"
echo "  sudo nginx -t               # Test Nginx config"
echo "  sudo systemctl status nginx # Check Nginx status"
echo "  netstat -tuln | grep 3000  # Check if app is listening"