#!/bin/bash
# Start Ginxsom FastCGI Application

# Configuration
FCGI_BINARY="./build/ginxsom-fcgi"
SOCKET_PATH="/tmp/ginxsom-fcgi.sock"
PID_FILE="/tmp/ginxsom-fcgi.pid"

# Function to cleanup on exit
cleanup() {
    echo "Cleaning up..."
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if kill -0 "$PID" 2>/dev/null; then
            echo "Stopping FastCGI process $PID"
            kill "$PID"
            sleep 1
            # Force kill if still running
            if kill -0 "$PID" 2>/dev/null; then
                kill -9 "$PID"
            fi
        fi
        rm -f "$PID_FILE"
    fi
    rm -f "$SOCKET_PATH"
    exit 0
}

# Setup signal handlers
trap cleanup SIGINT SIGTERM

# Check if binary exists
if [ ! -f "$FCGI_BINARY" ]; then
    echo "Error: FastCGI binary not found at $FCGI_BINARY"
    echo "Please run 'make' to build the application first"
    exit 1
fi

# Clean up old socket and pid file
rm -f "$SOCKET_PATH" "$PID_FILE"

# Start the FastCGI application
echo "Starting Ginxsom FastCGI application..."
echo "Socket: $SOCKET_PATH"
echo "Binary: $FCGI_BINARY"

# Use spawn-fcgi to start the application
spawn-fcgi -s "$SOCKET_PATH" -M 666 -u "$USER" -g "$USER" -f "$FCGI_BINARY" -P "$PID_FILE"

if [ $? -eq 0 ]; then
    echo "FastCGI application started successfully"
    echo "PID: $(cat $PID_FILE 2>/dev/null || echo 'unknown')"
    
    # Wait for the process to exit or be killed
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        echo "Monitoring process $PID (Press Ctrl+C to stop)"
        while kill -0 "$PID" 2>/dev/null; do
            sleep 1
        done
        echo "FastCGI process exited"
    fi
else
    echo "Failed to start FastCGI application"
    exit 1
fi

cleanup
