#!/bin/bash
# Only manages the exact Ornith SGLang process, bound to GPU1 and port8130.
set -euo pipefail
root=/home/lab/bench/ornith/sglang
case "${1:-status}" in
  status)
    curl --fail --silent --show-error --max-time 15 http://127.0.0.1:8130/health
    curl --fail --silent --show-error --max-time 15 http://127.0.0.1:8130/v1/models
    printf '\n'
    ;;
  start)
    if curl --fail --silent --max-time 3 http://127.0.0.1:8130/health >/dev/null; then
      printf 'SGLang already healthy on127.0.0.1:8130\n'; exit 0
    fi
    pane=$(tmux display-message -p -t sglang:Codex '#{pane_id}')
    test "$(tmux display-message -p -t "$pane" '#{pane_current_command}')" = bash || { printf 'Codex pane is busy; left untouched.\n'; exit 1; }
    tmux send-keys -t "$pane" -l "bash $root/start.sh 2>&1 | tee $root/server.log"
    tmux send-keys -t "$pane" Enter
    printf 'Started visibly in sglang:Codex. Use status after initialization.\n'
    ;;
  stop)
    /usr/bin/python3 - <<'PY'
import os, signal
from pathlib import Path
found=[]
for entry in Path('/proc').iterdir():
    if not entry.name.isdigit(): continue
    try:
        args=(entry/'cmdline').read_bytes().split(b'\0')
        env=(entry/'environ').read_bytes().split(b'\0')
    except (OSError, PermissionError): continue
    if len(args)>3 and args[:3]==[b'/home/lab/venvs/sglang/bin/python',b'-m',b'sglang.launch_server'] and b'ornith-sglang' in args and b'8130' in args and b'CUDA_VISIBLE_DEVICES=GPU-f4a988cb-c310-b618-5a9c-4462d4d33add' in env:
        found.append(int(entry.name))
if len(found)>1: raise SystemExit('Ambiguous process set; refusing to stop.')
if found:
    os.kill(found[0],signal.SIGINT)
    print('Sent graceful stop to SGLang PID',found[0])
else: print('No matching SGLang server running.')
PY
    ;;
  *) printf 'Usage: bash manage.sh start|stop|status\n'; exit 2 ;;
esac
