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

readonly HLCC_ROOT="/var/lib/guanghu/code-channel/candidates/hlcc-v16.0.1"
readonly HLCC_PID_FILE="${HLCC_ROOT}/hlcc.pid"
readonly HLCC_LOG_FILE="${HLCC_ROOT}/logs/hlcc.log"

if [[ "$(id -un)" != "guanghu" ]]; then
  echo "Refusing to start a domestic isolated candidate as any user other than guanghu." >&2
  exit 2
fi

if ! command -v curl >/dev/null 2>&1; then
  echo "Missing required command: curl" >&2
  exit 3
fi

if [[ -f "${HLCC_PID_FILE}" ]]; then
  readonly existing_pid="$(cat "${HLCC_PID_FILE}")"
  if kill -0 "${existing_pid}" 2>/dev/null; then
    echo "HLCC candidate is already running as PID ${existing_pid}."
    exit 0
  fi
fi

nohup "${HLCC_ROOT}/bin/hlcc" web \
  --work-path "${HLCC_ROOT}/data" \
  --config "${HLCC_ROOT}/config/app.ini" \
  >>"${HLCC_LOG_FILE}" 2>&1 &

readonly candidate_pid="$!"
echo "${candidate_pid}" > "${HLCC_PID_FILE}"
sleep 2

if ! kill -0 "${candidate_pid}" 2>/dev/null; then
  echo "HLCC candidate failed to remain running." >&2
  tail -n 80 "${HLCC_LOG_FILE}" >&2
  exit 5
fi

curl --fail --silent --show-error \
  "http://127.0.0.1:3340/api/v1/version"
echo
echo "HLCC isolated candidate is running on loopback only."
