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

ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
ENV_FILE="$ROOT/infra/.env.server"
BASE_COMPOSE="$ROOT/infra/docker-compose.yml"
SERVER_COMPOSE="$ROOT/infra/docker-compose.server.yml"
BUILD_FLAG="--build"
ACTIVATE="false"

for argument in "$@"; do
  case "$argument" in
    --no-build) BUILD_FLAG="" ;;
    --activate-server-profiles) ACTIVATE="true" ;;
    *) echo "Unknown argument: $argument" >&2; exit 2 ;;
  esac
done

if [ ! -f "$ENV_FILE" ]; then
  echo "Create infra/.env.server from infra/.env.server.example and replace all passwords." >&2
  exit 2
fi
command -v docker >/dev/null 2>&1 || { echo "Docker is not installed." >&2; exit 2; }
command -v nvidia-smi >/dev/null 2>&1 || { echo "nvidia-smi is not available." >&2; exit 2; }
nvidia-smi >/dev/null

mkdir -p "$ROOT/runtime/server-models"
if [ -n "$BUILD_FLAG" ]; then
  docker compose --env-file "$ENV_FILE" -f "$BASE_COMPOSE" -f "$SERVER_COMPOSE" up -d --build
else
  docker compose --env-file "$ENV_FILE" -f "$BASE_COMPOSE" -f "$SERVER_COMPOSE" up -d
fi

attempt=0
until curl -fsS http://localhost:8088/actuator/health | grep -q '"status":"UP"'; do
  attempt=$((attempt + 1))
  if [ "$attempt" -ge 60 ]; then
    echo "The platform did not become healthy within five minutes." >&2
    exit 1
  fi
  sleep 5
done

if [ "$ACTIVATE" = "true" ]; then
  for deployment_id in \
    runtime-vision-detector-gpu \
    runtime-vision-segmenter-gpu \
    runtime-thermal-gpu \
    runtime-change-gpu \
    runtime-pointcloud-server
  do
    curl -fsS -X POST -H 'Content-Type: application/json' \
      -d '{"force":false,"operator":"server-deployment-script","reason":"initialize server production profile"}' \
      "http://localhost:8088/api/v1/model-runtime-deployments/$deployment_id/activate" >/dev/null
    echo "Activated: $deployment_id"
  done
fi

echo "Server stack is ready: http://localhost:8088"
