#!/bin/bash
# =============================================================================
# MOMO Pro System -  External Access Fix Script
#  Purpose: Fix external network access issues for mo.wooo.work
#  Problem: Some external networks cannot access the web service
#  Solution: Update firewall rules to allow broader web access
#  Date: 2026-04-22
# =============================================================================

set -e

# Configuration
UAT_IP="114.32.151.246"  # This is the actual server IP
GCP_IP="35.194.233.141"
GCP_PROJECT="astral-gateway-484913-d7"

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

# Logging functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# =============================================================================
# Main Fix Functions
# =============================================================================

fix_nginx_configuration() {
    log_info "Updating Nginx configuration for external access..."
    
    # Create updated nginx config that allows all external access
    cat > /tmp/momo-nginx-fix.conf << 'EOF'
server {
    listen 80;
    server_name mo.wooo.work momo.wooo.work;

    # Redirect HTTP to HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name mo.wooo.work momo.wooo.work;

    # SSL certificates (Let's Encrypt)
    ssl_certificate /etc/letsencrypt/live/mo.wooo.work/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mo.wooo.work/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # Security headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # Upload size limit
    client_max_body_size 50M;

    # Logs
    access_log /var/log/nginx/momo_access.log;
    error_log /var/log/nginx/momo_error.log;

    # Main application proxy
    location / {
        proxy_pass http://127.0.0.1:5003;
        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;

        # WebSocket support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # Timeout settings
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # Buffer settings for large responses
        proxy_buffers 8 32k;
        proxy_buffer_size 64k;
    }

    # Health check endpoint
    location /health {
        access_log off;
        proxy_pass http://127.0.0.1:5003/health;
        proxy_set_header Host $host;
    }

    # Static files (if any)
    location /static/ {
        alias /app/static/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
EOF

    log_info "Nginx configuration template created"
}

update_firewall_rules() {
    log_info "Updating firewall rules for external web access..."
    
    # UFW Firewall updates (if this is the actual server)
    if [[ "$(hostname -I | grep -o '114\.32\.151\.246')" ]]; then
        log_info "Detected UAT server, updating UFW rules..."
        
        # Allow HTTP/HTTPS from anywhere
        sudo ufw allow 80/tcp comment 'HTTP from anywhere'
        sudo ufw allow 443/tcp comment 'HTTPS from anywhere'
        
        # Ensure web server can accept connections
        sudo ufw allow from 0.0.0.0/0 to any port 80,443 proto tcp comment 'Web services'
        
        log_info "UFW firewall rules updated"
    else
        log_warn "Not running on UAT server. Manual firewall update may be needed."
    fi
}

# GCP firewall function removed - focusing on local environment only

check_external_connectivity() {
    log_info "Testing external connectivity..."
    
    # Test from different perspectives
    local domains=("mo.wooo.work" "momo.wooo.work")
    
    for domain in "${domains[@]}"; do
        log_info "Testing $domain..."
        
        # DNS resolution
        if nslookup $domain > /dev/null 2>&1; then
            local ip=$(nslookup $domain | grep -A1 "Name:" | tail -1 | awk '{print $2}')
            log_info "  DNS: $domain -> $ip"
        else
            log_error "  DNS: Failed to resolve $domain"
        fi
        
        # HTTP connectivity
        if curl -s --connect-timeout 10 "http://$domain" | head -1 > /dev/null 2>&1; then
            log_info "  HTTP: Connection successful"
        else
            log_warn "  HTTP: Connection failed or redirected"
        fi
        
        # HTTPS connectivity
        if curl -s --connect-timeout 10 "https://$domain" | head -1 > /dev/null 2>&1; then
            log_info "  HTTPS: Connection successful"
        else
            log_error "  HTTPS: Connection failed"
        fi
    done
}

restart_services() {
    log_info "Restarting services..."
    
    # Restart nginx if it exists
    if command -v nginx > /dev/null 2>&1; then
        sudo nginx -t && sudo systemctl reload nginx || sudo systemctl restart nginx
        log_info "Nginx restarted"
    fi
    
    # Restart docker services if using docker
    if command -v docker > /dev/null 2>&1; then
        if docker ps | grep momo-app > /dev/null 2>&1; then
            docker restart momo-pro-system 2>/dev/null || true
            log_info "Docker services restarted"
        fi
    fi
}

# =============================================================================
# Main Execution
# =============================================================================

main() {
    echo ""
    echo "${GREEN}============================================================================${NC}"
    echo "${GREEN}     MOMO Pro System - External Access Fix Tool${NC}"
    echo "${GREEN}============================================================================${NC}"
    echo ""
    
    log_info "Starting external access fix for mo.wooo.work..."
    echo ""
    
    # Step 1: Update configurations
    log_info "Step 1: Updating configurations..."
    fix_nginx_configuration
    
    # Step 2: Update firewall rules
    echo ""
    log_info "Step 2: Updating firewall rules..."
    update_firewall_rules
    
    # Step 3: Skip GCP firewall (local environment only)
    echo ""
    log_info "Step 3: Skipping GCP firewall (local environment only)..."
    
    # Step 4: Restart services
    echo ""
    log_info "Step 4: Restarting services..."
    restart_services
    
    # Step 5: Test connectivity
    echo ""
    log_info "Step 5: Testing external connectivity..."
    check_external_connectivity
    
    echo ""
    log_info "External access fix completed!"
    echo ""
    echo "${YELLOW}Next steps:${NC}"
    echo "1. Verify https://mo.wooo.work is accessible from different networks"
    echo "2. Check SSL certificate validity"
    echo "3. Monitor application logs for any issues"
    echo "4. Test from mobile networks and different ISPs"
    echo ""
    
    if [[ -f /tmp/momo-nginx-fix.conf ]]; then
        echo "${GREEN}Nginx configuration template created at: /tmp/momo-nginx-fix.conf${NC}"
        echo "Please manually apply this configuration if needed."
    fi
}

# Run main function
main "$@"
