# Function to cleanup on exit
cleanup() {
    log "Shutting down..."
    stop_server
    exit 0
}

# Trap Ctrl+C (SIGINT) and other termination signals
trap cleanup SIGINT SIGTERM

#!/bin/bash

# Log function for better visibility
log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

# Function to check if node server is running
is_server_running() {
    if pgrep -f "npm run start" > /dev/null; then
        return 0  # Server is running
    else
        return 1  # Server is not running
    fi
}

# Function to stop the server
stop_server() {
    if is_server_running; then
        log "Stopping Node server..."
        pkill -f "npm run start"
        sleep 2  # Wait for the server to stop

        if is_server_running; then
            log "ERROR: Failed to stop Node server"
            exit 1
        else
            log "Node server stopped successfully"
        fi
    else
        log "Node server is not running"
    fi
}

# Function to start the server
start_server() {
    if ! is_server_running; then
        log "Starting Node server..."
        # Start the server in foreground
        npm run start &
        NODE_PID=$!
        sleep 2  # Wait for the server to start

        if is_server_running; then
            log "Node server started successfully"
            # Bring the process to foreground
            fg %1
        else
            log "ERROR: Failed to start Node server"
            exit 1
        fi
    else
        log "Node server is already running"
    fi
}

# Function to restart the server
restart_server() {
    log "Restarting Node server..."
    stop_server
    start_server
}

# Pull updates from main branch
log "Pulling updates from main branch..."
if ! git pull origin main; then
    log "ERROR: Failed to pull updates from Git"
    exit 1
fi
log "Git pull completed successfully"

# Stop the server
stop_server

# Run database migrations
log "Running database migrations..."
if ! npx mikro-orm-esm migration:up; then
    log "ERROR: Failed to run database migrations"
    exit 1
fi
log "Database migrations completed successfully"

# Start the server
start_server

# Monitor server and restart if it stops
log "Server started. You can now interact with the Node.js console."
wait $NODE_PID