#!/bin/bash

# Run npm run dev in the background and capture its PID
sudo npm run dev &

# Give some time for the server to start
sleep 20

# Set a flag to track server status
server_started=false

# Loop to continuously check if the server is accessible and process is running
while true; do
    # Check if the server is accessible
    if curl -sSf "http://localhost:3000" >/dev/null; then
        echo "Server started successfully."
        server_started=true
        break
    else
        echo "Waiting for server to start..."
    fi

    # Check if the process is still running
    if ! pgrep -f 'sudo npm run dev' >/dev/null; then
        echo "npm run dev process terminated unexpectedly."
        break
    fi

    # Wait for a few seconds before checking again
    sleep 5
done

# If the server started and the process is running, wait for user input to stop the server
if [ "$server_started" = true ]; then
    # Get the PID of npm run dev
    PID=$(pgrep -f 'sudo npm run dev')

    # Kill the npm run dev process if it's still running
    if [ -n "$PID" ]; then
        kill "$PID"
        echo "npm run dev process killed."
    fi
fi


