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

export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

readonly FREE_GIB_FLOOR="${FREE_GIB_FLOOR:-360}"
readonly WINDOWS_ROOT="/mnt/d/NDC_MISSIONCORE"
readonly COMPUTE_ROOT="${WINDOWS_ROOT}/workspace/mission-core-compute"
readonly TOOL_ROOT="/srv/mission-core-cvat/tools/e2-import"
readonly SECRET_FILE="${WINDOWS_ROOT}/secrets/cvat/admin.env"
readonly WORKSPACE_ID="e3-cvat-review-ca599521e345446ca8e9af5a9013062099278e7317f83ff89740c6b092ddc52f"
readonly WORKSPACE_ROOT="${WINDOWS_ROOT}/runtime/annotation/imports/LAB-E3/${WORKSPACE_ID}"
readonly E2_WORKSPACE_ID="annotation-workspace-9a950d1c37d56dc12cc285b13c5addd7795285879cbcb1fbb2d5811c3c69821a"
readonly IMAGES_ZIP="${WINDOWS_ROOT}/runtime/annotation/imports/LAB-E2/${E2_WORKSPACE_ID}/cvat/images.zip"
readonly REPORT_ROOT="${WINDOWS_ROOT}/runtime/annotation/cvat/reports"

if [[ "${EUID}" -ne 0 ]]; then
  echo "import_e3_review.sh must run as root" >&2
  exit 2
fi

free_gib() {
  df -BG --output=avail "${WINDOWS_ROOT}" | tail -n 1 | tr -dc '0-9'
}

guard_disk() {
  local stage="$1"
  local free
  free="$(free_gib)"
  printf 'disk_guard stage=%s free_gib=%s floor_gib=%s\n' \
    "${stage}" "${free}" "${FREE_GIB_FLOOR}"
  if (( free < FREE_GIB_FLOOR )); then
    echo "D: free-space floor crossed; refusing further writes" >&2
    exit 3
  fi
}

wait_for_cvat() {
  local attempt http_code
  for attempt in $(seq 1 60); do
    http_code="$(
      curl --silent --output /dev/null --write-out '%{http_code}' \
        "http://localhost:8080/api/server/about" || true
    )"
    if [[ "${http_code}" == "200" ]]; then
      printf 'cvat_ready attempt=%s\n' "${attempt}"
      return 0
    fi
    sleep 2
  done
  echo "CVAT API did not become ready within 120 seconds" >&2
  return 1
}

test -x "${TOOL_ROOT}/venv/bin/python"
test -f "${SECRET_FILE}"
test -f "${WORKSPACE_ROOT}/manifest.json"
test -f "${IMAGES_ZIP}"
test -f "${COMPUTE_ROOT}/cvat/import_e2_workspace.py"
test -f "${COMPUTE_ROOT}/cvat/import_e3_review.py"
guard_disk preflight

set -a
# shellcheck disable=SC1090
. "${SECRET_FILE}"
set +a

wait_for_cvat
report="${REPORT_ROOT}/lab-e3-cvat-import-$(date -u +%Y%m%dT%H%M%SZ).json"
"${TOOL_ROOT}/venv/bin/python" "${COMPUTE_ROOT}/cvat/import_e3_review.py" \
  --server "http://localhost:8080" \
  --username "${CVAT_ADMIN_USERNAME}" \
  --password-env CVAT_ADMIN_PASSWORD \
  --workspace "${WORKSPACE_ROOT}" \
  --images-zip "${IMAGES_ZIP}" \
  --report "${report}"

guard_disk imported
printf 'import_report=%s\n' "${report}"
