#!/usr/bin/env sh
set -eu

if [ "$#" -lt 2 ]; then
  echo "Usage: sh scripts/setup_server_model.sh <model-group> <version> [model.onnx] [labels.txt] [secondary.onnx]" >&2
  exit 2
fi

GROUP="$1"
VERSION="$2"
MODEL_PATH="${3:-}"
LABELS_PATH="${4:-}"
SECONDARY_PATH="${5:-}"
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
TARGET_ROOT="$ROOT/runtime/server-models/$GROUP/$VERSION"

case "$VERSION" in
  v1.0.0|v1.1.0) ;;
  *) echo "Unsupported version: $VERSION" >&2; exit 2 ;;
esac

if [ "$GROUP" = "pointcloud-analyzer" ]; then
  echo "Open3D geometry analysis does not require a model artifact."
  exit 0
fi

case "$GROUP" in
  vision-detector|vision-segmenter|change-detector|thermal-analyzer) ;;
  *) echo "Unsupported model group: $GROUP" >&2; exit 2 ;;
esac

if [ ! -f "$MODEL_PATH" ]; then
  echo "The ONNX model file does not exist: $MODEL_PATH" >&2
  exit 2
fi
if [ ! -f "$LABELS_PATH" ]; then
  echo "The labels file does not exist: $LABELS_PATH" >&2
  exit 2
fi

mkdir -p "$TARGET_ROOT"
cp "$MODEL_PATH" "$TARGET_ROOT/model.onnx"
cp "$LABELS_PATH" "$TARGET_ROOT/labels.txt"
echo "Installed model: $TARGET_ROOT/model.onnx"
sha256sum "$TARGET_ROOT/model.onnx"

if [ "$GROUP" = "thermal-analyzer" ]; then
  if [ ! -f "$SECONDARY_PATH" ]; then
    echo "The thermal analyzer requires a PatchCore ONNX file." >&2
    exit 2
  fi
  cp "$SECONDARY_PATH" "$TARGET_ROOT/patchcore.onnx"
  echo "Installed secondary model: $TARGET_ROOT/patchcore.onnx"
fi
