#!/bin/sh
set -eu

export HWLAB_SERVICE_ID="hwlab-edge-proxy"
export HWLAB_ARTIFACT_KIND="node-command"
export HWLAB_SERVICE_ENTRYPOINT="cmd/hwlab-edge-proxy/main.mjs"
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}}"
edge_port="${HWLAB_EDGE_PORT:-${PORT:-${HWLAB_PORT:-6667}}}"
export PORT="${PORT:-$edge_port}"
export HWLAB_PORT="$PORT"
export HWLAB_EDGE_PORT="$edge_port"
export HWLAB_EDGE_LISTEN="${HWLAB_EDGE_LISTEN:-0.0.0.0:$edge_port}"

node_bin="${HWLAB_NODE_COMMAND:-}"
if [ -z "$node_bin" ]; then
  if command -v node >/dev/null 2>&1; then
    node_bin="$(command -v node)"
  elif [ -x /usr/local/bin/node ]; then
    node_bin="/usr/local/bin/node"
  else
    echo "hwlab-edge-proxy boot failed: node not found" >&2
    exit 127
  fi
fi

exec "$node_bin" cmd/hwlab-edge-proxy/main.mjs
