#!/usr/bin/env bash
# Start/stop the CUAS DGX inference server (PyTorch RawFCN, cuDNN) in the NGC container.
# By Claude on 06/20/2026.  Run on the DGX (elphel@192.168.0.62).
#   start|stop|logs|status        env: RUN=runs/<model>  RUN2=runs/<l2>  PORT=5577
set -euo pipefail
NAME=cuas_infer
IMG=nvcr.io/nvidia/pytorch:25.10-py3
CODE=/home/elphel/c5p_dnn
RUN="${RUN:-runs/weighted9_pm_s}"
RUN2="${RUN2:-}"                 # optional Layer-2 run dir; empty -> L1-only. By Claude 06/22/2026
PORT="${PORT:-5577}"
case "${1:-start}" in
  start)
    docker rm -f "$NAME" >/dev/null 2>&1 || true
    L2ARG=""; [ -n "$RUN2" ] && L2ARG="--l2run $RUN2"
    docker run -d --name "$NAME" --gpus all --network host \
      -v "$CODE":/work -w /work "$IMG" \
      python infer_server.py --run "$RUN" $L2ARG --port "$PORT" >/dev/null
    echo "started $NAME (run=$RUN l2=${RUN2:-off} port=$PORT)"; sleep 3; docker logs "$NAME"
    ;;
  stop)   docker rm -f "$NAME" >/dev/null 2>&1 && echo "stopped" || echo "not running" ;;
  logs)   docker logs --tail 60 "$NAME" ;;
  status) docker ps --filter "name=$NAME" --format "{{.Names}} {{.Status}}" ;;
  *) echo "usage: $0 {start|stop|logs|status}  (env: RUN=, RUN2=, PORT=)"; exit 1 ;;
esac
