#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib.sh
source "${SCRIPT_DIR}/lib.sh"

CONFIG_IN_CONTAINER="${CONFIG_IN_CONTAINER:-/workspace/mvp/configs/dev.yaml}"
LOG_PATH="${LOG_PATH:-/private/common/logs/argus_mvp_api.log}"
PID_PATH="${PID_PATH:-/private/common/run/argus_mvp_api.pid}"

echo "[host] starting mvp v2 api in head container: ${HEAD_CONTAINER}"

dexec "${HEAD_CONTAINER}" bash -lc "mkdir -p \"$(dirname "${LOG_PATH}")\" \"$(dirname "${PID_PATH}")\""

# Note: requires /workspace/mvp/py to be present in the container (mounted).
# Escape $ so that the command substitution happens in the container, not on the host.
dexec "${HEAD_CONTAINER}" bash -lc "if test -f '${PID_PATH}'; then pid=\$(cat '${PID_PATH}'); if kill -0 \"\${pid}\" >/dev/null 2>&1; then echo 'already_running'; exit 0; fi; fi"

if [[ -z "${MVP_INTERNAL_TOKEN:-}" ]]; then
  echo "ERROR: MVP_INTERNAL_TOKEN env var must be set on host (will be passed into container)" >&2
  exit 1
fi

env_args=(-e "MVP_INTERNAL_TOKEN=${MVP_INTERNAL_TOKEN}")
# If host does not provide it, fall back to the dev default used by docker-compose (kept in sync).
env_args+=(-e "SFTPGO_ADMIN_PASSWORD=${SFTPGO_ADMIN_PASSWORD:-my-dev-sftpgo-admin}")
if [[ -n "${WANDB_API_KEY:-}" ]]; then
  env_args+=(-e "WANDB_API_KEY=${WANDB_API_KEY}")
fi

docker exec -d "${env_args[@]}" "${HEAD_CONTAINER}" bash -lc "nohup python3 /workspace/mvp/py/server.py --config '${CONFIG_IN_CONTAINER}' >>'${LOG_PATH}' 2>&1 & echo \$! >'${PID_PATH}'"

echo "[host] started; pid stored in ${PID_PATH} (container path)"
echo "[host] logs: ${LOG_PATH} (container path)"
