#!/bin/bash
# Start a SGLang baseline server for DeepSeek-V4-Flash on H200.
set -e

cd /data/user1/yy
mkdir -p logs

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
source "${SCRIPT_DIR}/config.env"

export PATH="${VENV_SERVER}/bin:$PATH"
export PYTHONUNBUFFERED=1
export SGLANG_LOG_LEVEL=info

TP=8
LOG="/data/user1/yy/logs/dsv4_h200_sglang_tp${TP}_$(date +%Y%m%d_%H%M%S).log"
PID_FILE="/data/user1/yy/dsv4_h200_sglang.pid"

export TMPDIR=/data/user1/yy/tmp
export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7

echo "=== Starting DeepSeek-V4-Flash SGLang baseline (TP=$TP) ==="
echo "Model: $MODEL_PATH"
echo "Port: $PORT"
echo "Log: $LOG"

rm -f "$PID_FILE"
nohup "${VENV_SERVER}/bin/sglang" serve \
    --trust-remote-code \
    --model-path "$MODEL_PATH" \
    --tp "$TP" \
    --moe-runner-backend marlin \
    --host 0.0.0.0 \
    --port "$PORT" \
    > "$LOG" 2>&1 &
PID=$!
echo $PID > "$PID_FILE"
echo "PID: $PID"
echo "Waiting for health..."

for i in $(seq 1 240); do
    # curl --fail treats any HTTP >=400 as an error, so 503 won't pass.
    if curl --fail --silent --show-error --max-time 5 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then
        echo "Server is ready at http://127.0.0.1:$PORT"
        echo "Log: $LOG"
        exit 0
    fi
    if ! kill -0 $PID 2>/dev/null; then
        echo "ERROR: Server exited early"
        tail -200 "$LOG"
        exit 1
    fi
    echo "Waiting... ($i/240)"
    sleep 5
done

echo "ERROR: Server not healthy after 240 retries"
tail -200 "$LOG"
exit 1
