#!/bin/bash
set -e

# Check if model path is provided as first argument
if [ $# -lt 1 ]; then
    echo "Usage: $0 <model_path> [additional_sglang_args...]"
    echo "Example: $0 /path/to/model --port 30000 --dp 8 --is-embedding"
    exit 1
fi

MODEL_PATH="$1"
shift  # Remove the first argument (model_path)

# All remaining arguments will be passed to sglang.launch_server
SGLANG_ARGS="$@"

# Default port for checking if server is running
DEFAULT_PORT=30000
PORT=$DEFAULT_PORT

# Extract port from arguments if provided
for arg in $SGLANG_ARGS; do
    if [[ "$prev_arg" == "--port" ]]; then
        PORT="$arg"
        break
    fi
    prev_arg="$arg"
done

echo "Checking if sglang server is already running on port ${PORT}..."
if curl -s http://localhost:${PORT}/get_model_info > /dev/null; then
    echo "Sglang server is already running on port ${PORT}!"
else
    echo "Starting sglang server on port ${PORT}..."
    python -m sglang.launch_server --model-path "${MODEL_PATH}" --host 0.0.0.0 ${SGLANG_ARGS} 2>&1 &
    
    echo "Waiting for sglang server to be ready..."
    while ! curl -s http://localhost:${PORT}/get_model_info > /dev/null; do
        sleep 10
    done
    echo "Sglang server is ready!"
fi
