#!/bin/bash

# Switch Apache from port 8080 to port 80
# Usage: ./switch_to_port_80.sh

set -e  # Exit on error

echo "=== Switching Apache to Port 80 ==="

# Check if running as root (needed for port 80)
if [ "$EUID" -ne 0 ]; then 
    echo "Port 80 requires root privileges. Please run with sudo:"
    echo "sudo ./switch_to_port_80.sh"
    exit 1
fi

# Find Apache config file
HTTPD_CONF=""
if [ -f "/opt/homebrew/etc/httpd/httpd.conf" ]; then
    HTTPD_CONF="/opt/homebrew/etc/httpd/httpd.conf"
elif [ -f "/usr/local/etc/httpd/httpd.conf" ]; then
    HTTPD_CONF="/usr/local/etc/httpd/httpd.conf"
elif [ -f "/etc/apache2/httpd.conf" ]; then
    HTTPD_CONF="/etc/apache2/httpd.conf"
else
    echo "ERROR: Could not find httpd.conf"
    exit 1
fi

echo "Found Apache config: $HTTPD_CONF"

# Backup config
cp "$HTTPD_CONF" "$HTTPD_CONF.bak.$(date +%Y%m%d_%H%M%S)"
echo "Config backed up"

# Check if nginx is running on port 80
if lsof -iTCP:80 -sTCP:LISTEN -P | grep -q nginx; then
    echo "Stopping nginx (using port 80)..."
    if command -v brew &> /dev/null; then
        sudo -u $(stat -f '%Su' /opt/homebrew 2>/dev/null || echo $SUDO_USER) brew services stop nginx 2>/dev/null || true
    fi
    # Force kill any remaining nginx processes
    pkill -QUIT nginx 2>/dev/null || true
    sleep 2
fi

# Change Listen directive from 8080 to 80
echo "Updating Apache config..."
sed -i '' 's/^Listen 8080$/Listen 80/' "$HTTPD_CONF"

# Verify change
if grep -q "^Listen 80$" "$HTTPD_CONF"; then
    echo "✓ Config updated successfully"
else
    echo "ERROR: Failed to update config"
    exit 1
fi

# Restart Apache
echo "Restarting Apache..."
if command -v brew &> /dev/null; then
    sudo -u $(stat -f '%Su' /opt/homebrew 2>/dev/null || echo $SUDO_USER) brew services restart httpd
else
    apachectl restart
fi

sleep 2

# Verify Apache is on port 80
if lsof -iTCP:80 -sTCP:LISTEN -P | grep -q httpd; then
    echo "✓ SUCCESS: Apache is now running on port 80"
    lsof -iTCP:80 -sTCP:LISTEN -P | grep httpd
else
    echo "ERROR: Apache is not listening on port 80"
    echo "Check logs: tail -f /opt/homebrew/var/log/httpd/error_log"
    exit 1
fi

echo ""
echo "Done! Your site is now accessible without :8080"
