#!/bin/sh
set -eu

export HWLAB_SERVICE_ID="hwlab-cloud-api"
export HWLAB_ARTIFACT_KIND="bun-command"
export HWLAB_SERVICE_ENTRYPOINT="cmd/hwlab-cloud-api/main.ts"
export HWLAB_RUNTIME_MODE="${HWLAB_RUNTIME_MODE:-env-reuse-git-mirror-checkout}"
export HWLAB_COMMIT_ID="${HWLAB_BOOT_COMMIT:?HWLAB_BOOT_COMMIT is required}"
export HWLAB_REVISION="${HWLAB_BOOT_COMMIT}"
export HWLAB_IMAGE="${HWLAB_ENVIRONMENT_IMAGE:-${HWLAB_IMAGE:-}}"
export HWLAB_IMAGE_DIGEST="${HWLAB_ENVIRONMENT_DIGEST:-${HWLAB_IMAGE_DIGEST:-unknown}}"
export PORT="${PORT:-${HWLAB_CLOUD_API_PORT:-${HWLAB_PORT:-6667}}}"
export HWLAB_PORT="$PORT"
export HWLAB_CLOUD_API_PORT="$PORT"
export HWLAB_CODE_AGENT_AGENTRUN_SOURCE_COMMIT="${HWLAB_CODE_AGENT_AGENTRUN_SOURCE_COMMIT:-${HWLAB_BOOT_COMMIT}}"
export HWLAB_CODE_AGENT_AGENTRUN_REPO_URL="${HWLAB_CODE_AGENT_AGENTRUN_REPO_URL:-${HWLAB_BOOT_READ_URL:-http://git-mirror-http.devops-infra.svc.cluster.local/pikasTech/HWLAB.git}}"
export HWLAB_CODE_AGENT_WORKSPACE="${HWLAB_CODE_AGENT_WORKSPACE:-$PWD}"
export HWLAB_CODE_AGENT_CODEX_WORKSPACE="${HWLAB_CODE_AGENT_CODEX_WORKSPACE:-$HWLAB_CODE_AGENT_WORKSPACE}"
export CODEX_HOME="${CODEX_HOME:-/codex-home}"

if [ -z "${HWLAB_CODE_AGENT_CODEX_COMMAND:-}" ] || [ "${HWLAB_CODE_AGENT_CODEX_COMMAND:-}" = "/app/node_modules/.bin/codex" ]; then
  export HWLAB_CODE_AGENT_CODEX_COMMAND="$PWD/node_modules/.bin/codex"
fi
if [ -z "${HWLAB_PREINSTALLED_SKILLS_DIR:-}" ] || [ "${HWLAB_PREINSTALLED_SKILLS_DIR:-}" = "/app/skills" ]; then
  export HWLAB_PREINSTALLED_SKILLS_DIR="$PWD/skills"
fi
export HWLAB_USER_SKILLS_DIR="${HWLAB_USER_SKILLS_DIR:-/data/user-skills}"
if [ -z "${HWLAB_CODE_AGENT_SKILLS_DIRS:-}" ] || [ "${HWLAB_CODE_AGENT_SKILLS_DIRS:-}" = "/app/skills:/data/user-skills" ]; then
  export HWLAB_CODE_AGENT_SKILLS_DIRS="$HWLAB_PREINSTALLED_SKILLS_DIR:$HWLAB_USER_SKILLS_DIR"
fi

bun_bin="${HWLAB_BUN_COMMAND:-}"
if [ -z "$bun_bin" ]; then
  if command -v bun >/dev/null 2>&1; then
    bun_bin="$(command -v bun)"
  elif [ -x /usr/local/bin/bun ]; then
    bun_bin="/usr/local/bin/bun"
  elif [ -x ./node_modules/.bin/bun ]; then
    bun_bin="./node_modules/.bin/bun"
  else
    echo "hwlab-cloud-api boot failed: bun not found" >&2
    exit 127
  fi
fi

exec "$bun_bin" run cmd/hwlab-cloud-api/main.ts
