#!/bin/bash

# Pilipili Server - Main Entry Point
# A spicy little web server written in pure Bash 🌶️
# Version: 1.0.0

set -euo pipefail

# Default values
DEFAULT_PORT=8080
DEFAULT_DIR="./public"
VERSION="1.0.0"

# Help text
show_help() {
    cat << 'EOF'
Pilipili Server - A spicy little web server 🌶️

USAGE:
    pilipili-server [OPTIONS] [DIRECTORY]

OPTIONS:
    -p, --port PORT     Port to listen on (default: 8080)
    -h, --help          Show this help message
    -v, --version       Show version information
    --verbose           Enable verbose logging

EXAMPLES:
    pilipili-server                     # Serve ./public on port 8080
    pilipili-server -p 3000            # Serve on port 3000
    pilipili-server ./docs             # Serve ./docs directory
    pilipili-server --verbose          # Enable detailed logging

DIRECTORY:
    Directory to serve files from (default: ./public)

For more information, visit: https://github.com/Baraka-Malila/pilipili-server
EOF
}

show_version() {
    echo "Pilipili Server v${VERSION} 🌶️"
    echo "A spicy little web server written in pure Bash"
}

# Parse arguments
SERVE_DIR="$DEFAULT_DIR"
PORT="$DEFAULT_PORT"
VERBOSE=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -p|--port)
            PORT="$2"
            shift 2
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        -v|--version)
            show_version
            exit 0
            ;;
        --verbose)
            VERBOSE=true
            shift
            ;;
        -*)
            echo "Unknown option: $1" >&2
            echo "Use --help for usage information" >&2
            exit 1
            ;;
        *)
            SERVE_DIR="$1"
            shift
            ;;
    esac
done

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Export variables for sub-scripts
export PORT SERVE_DIR VERBOSE

# Start the main server
echo "🌶️ Starting Pilipili Server v${VERSION}..."
echo "📁 Serving: $SERVE_DIR"
echo "🔗 URL: http://localhost:$PORT"
echo "⏹️  Press Ctrl+C to stop"
echo

# Check if socat is available (better than netcat for this)
if command -v socat >/dev/null 2>&1; then
    echo "Using socat for robust connection handling..."
    # Export environment variables for the handler script
    export SERVE_DIR PORT VERBOSE SERVER_NAME="Pilipili-Server/1.0"
    # Start socat with fork option to handle multiple connections
    exec socat TCP4-LISTEN:$PORT,fork,reuseaddr EXEC:"$SCRIPT_DIR/server.sh"
else
    echo "⚠️  socat not found - falling back to basic netcat implementation"
    echo "   For better performance, install socat: sudo apt-get install socat"
    echo
    
    # Basic netcat fallback
    while true; do
        echo "Waiting for connection on port $PORT..."
        (
            echo -e "HTTP/1.1 200 OK\r"
            echo -e "Content-Type: text/html\r"
            echo -e "Connection: close\r"
            echo -e "\r"
            if [ -f "$SERVE_DIR/index.html" ]; then
                cat "$SERVE_DIR/index.html"
            else
                echo "<h1>Pilipili Server 🌶️</h1><p>Server is running but no index.html found in $SERVE_DIR</p>"
            fi
        ) | nc -l "$PORT" -q 1 2>/dev/null || true
        sleep 0.1
    done
fi
