#!/bin/bash
# Restart Ginxsom Development Environment
# Combines nginx and FastCGI restart operations for debugging

# Configuration
FCGI_BINARY="./build/ginxsom-fcgi"
SOCKET_PATH="/tmp/ginxsom-fcgi.sock"
PID_FILE="/tmp/ginxsom-fcgi.pid"
NGINX_CONFIG="config/local-nginx.conf"

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

echo -e "${YELLOW}=== Ginxsom Development Environment Restart ===${NC}"
echo "Starting full restart sequence..."

# Function to check if a process is running
check_process() {
    local pid=$1
    kill -0 "$pid" 2>/dev/null
}

# Function to wait for process to stop
wait_for_stop() {
    local pid=$1
    local timeout=${2:-10}
    local count=0
    
    while check_process "$pid" && [ $count -lt $timeout ]; do
        sleep 1
        ((count++))
    done
    
    if check_process "$pid"; then
        echo -e "${RED}Warning: Process $pid still running after ${timeout}s${NC}"
        return 1
    fi
    return 0
}

# Step 1: Stop nginx
echo -e "\n${YELLOW}1. Stopping nginx...${NC}"
if pgrep -f "nginx.*${NGINX_CONFIG}" > /dev/null; then
    echo "Found running nginx processes, stopping..."
    nginx -p . -c "${NGINX_CONFIG}" -s stop 2>/dev/null
    sleep 2
    
    # Force kill any remaining nginx processes
    NGINX_PIDS=$(pgrep -f "nginx.*${NGINX_CONFIG}")
    if [ ! -z "$NGINX_PIDS" ]; then
        echo "Force killing remaining nginx processes: $NGINX_PIDS"
        kill -9 $NGINX_PIDS 2>/dev/null
    fi
    echo -e "${GREEN}nginx stopped${NC}"
else
    echo "nginx not running"
fi

# Step 2: Stop FastCGI
echo -e "\n${YELLOW}2. Stopping FastCGI application...${NC}"

# Method 1: Stop via PID file
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    echo "Found PID file with process $PID"
    if check_process "$PID"; then
        echo "Stopping FastCGI process $PID"
        kill "$PID"
        if wait_for_stop "$PID" 5; then
            echo -e "${GREEN}FastCGI process stopped gracefully${NC}"
        else
            echo "Force killing FastCGI process $PID"
            kill -9 "$PID" 2>/dev/null
        fi
    else
        echo "PID $PID not running, cleaning up PID file"
    fi
    rm -f "$PID_FILE"
fi

# Method 2: Kill any remaining ginxsom-fcgi processes
FCGI_PIDS=$(pgrep -f "ginxsom-fcgi")
if [ ! -z "$FCGI_PIDS" ]; then
    echo "Found additional FastCGI processes: $FCGI_PIDS"
    kill $FCGI_PIDS 2>/dev/null
    sleep 2
    # Force kill if still running
    FCGI_PIDS=$(pgrep -f "ginxsom-fcgi")
    if [ ! -z "$FCGI_PIDS" ]; then
        echo "Force killing FastCGI processes: $FCGI_PIDS"
        kill -9 $FCGI_PIDS 2>/dev/null
    fi
fi

# Method 3: Clean up socket
if [ -S "$SOCKET_PATH" ]; then
    echo "Removing old socket: $SOCKET_PATH"
    rm -f "$SOCKET_PATH"
fi

echo -e "${GREEN}FastCGI cleanup complete${NC}"

# Step 3: Check if binary exists and is up to date
echo -e "\n${YELLOW}3. Checking FastCGI binary...${NC}"
if [ ! -f "$FCGI_BINARY" ]; then
    echo -e "${RED}Error: FastCGI binary not found at $FCGI_BINARY${NC}"
    echo "Building application..."
    make
    if [ $? -ne 0 ]; then
        echo -e "${RED}Build failed! Cannot continue.${NC}"
        exit 1
    fi
else
    echo "FastCGI binary found: $FCGI_BINARY"
    
    # Check if source is newer than binary
    if [ "src/main.c" -nt "$FCGI_BINARY" ] || [ "Makefile" -nt "$FCGI_BINARY" ]; then
        echo "Source files are newer than binary, rebuilding..."
        make
        if [ $? -ne 0 ]; then
            echo -e "${RED}Build failed! Cannot continue.${NC}"
            exit 1
        fi
        echo -e "${GREEN}Rebuild complete${NC}"
    fi
fi

# Step 4: Start FastCGI
echo -e "\n${YELLOW}4. Starting FastCGI application...${NC}"
echo "Socket: $SOCKET_PATH"
echo "Binary: $FCGI_BINARY"

# Check if spawn-fcgi is available
if ! command -v spawn-fcgi &> /dev/null; then
    echo -e "${RED}Error: spawn-fcgi not found. Please install it:${NC}"
    echo "  Ubuntu/Debian: sudo apt-get install spawn-fcgi"
    echo "  macOS: brew install spawn-fcgi"
    exit 1
fi

# Start FastCGI application with stderr logging (no wrapper needed)
# Create stderr log with timestamp
echo "FastCGI starting at $(date)" > logs/fcgi-stderr.log
spawn-fcgi -s "$SOCKET_PATH" -M 666 -u "$USER" -g "$USER" -f "$FCGI_BINARY" -P "$PID_FILE" 2>>logs/fcgi-stderr.log

if [ $? -eq 0 ] && [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    echo -e "${GREEN}FastCGI application started successfully${NC}"
    echo "PID: $PID"
    
    # Verify it's actually running
    if check_process "$PID"; then
        echo -e "${GREEN}Process confirmed running${NC}"
    else
        echo -e "${RED}Warning: Process may have crashed immediately${NC}"
        exit 1
    fi
else
    echo -e "${RED}Failed to start FastCGI application${NC}"
    exit 1
fi

# Step 5: Start nginx
echo -e "\n${YELLOW}5. Starting nginx...${NC}"
if [ ! -f "$NGINX_CONFIG" ]; then
    echo -e "${RED}Error: nginx config not found at $NGINX_CONFIG${NC}"
    exit 1
fi

# Test nginx configuration first
nginx -p . -c "$NGINX_CONFIG" -t
if [ $? -ne 0 ]; then
    echo -e "${RED}nginx configuration test failed!${NC}"
    exit 1
fi

# Start nginx
nginx -p . -c "$NGINX_CONFIG"
if [ $? -eq 0 ]; then
    echo -e "${GREEN}nginx started successfully${NC}"
    
    # Verify nginx is running
    sleep 1
    if pgrep -f "nginx.*${NGINX_CONFIG}" > /dev/null; then
        echo -e "${GREEN}nginx confirmed running${NC}"
    else
        echo -e "${RED}Warning: nginx may have crashed${NC}"
        exit 1
    fi
else
    echo -e "${RED}Failed to start nginx${NC}"
    exit 1
fi

# Step 6: Final status check
echo -e "\n${YELLOW}6. Final status check...${NC}"

# Check FastCGI
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if check_process "$PID"; then
        echo -e "${GREEN}✓ FastCGI running (PID: $PID)${NC}"
    else
        echo -e "${RED}✗ FastCGI not running${NC}"
    fi
else
    echo -e "${RED}✗ FastCGI PID file missing${NC}"
fi

# Check nginx
if pgrep -f "nginx.*${NGINX_CONFIG}" > /dev/null; then
    NGINX_PIDS=$(pgrep -f "nginx.*${NGINX_CONFIG}" | tr '\n' ' ')
    echo -e "${GREEN}✓ nginx running (PIDs: $NGINX_PIDS)${NC}"
else
    echo -e "${RED}✗ nginx not running${NC}"
fi

# Check socket
if [ -S "$SOCKET_PATH" ]; then
    echo -e "${GREEN}✓ FastCGI socket exists: $SOCKET_PATH${NC}"
else
    echo -e "${RED}✗ FastCGI socket missing: $SOCKET_PATH${NC}"
fi

echo -e "\n${GREEN}=== Restart sequence complete ===${NC}"
echo -e "${YELLOW}Server should be available at: http://localhost:9001${NC}"
echo -e "${YELLOW}To stop all processes, run: nginx -p . -c $NGINX_CONFIG -s stop && kill \$(cat $PID_FILE 2>/dev/null)${NC}"
echo -e "${YELLOW}To monitor logs, check: logs/error.log, logs/access.log, and logs/fcgi-stderr.log${NC}"