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

ARGUS_BUILD_UID=${ARGUS_BUILD_UID:-2133}
ARGUS_BUILD_GID=${ARGUS_BUILD_GID:-2015}
AGENT_ROOT=${AGENT_ROOT:-/private/argus/agent}
PREPARED_FLAG="/tmp/.metric_node_prepared"

export DEBIAN_FRONTEND=${DEBIAN_FRONTEND:-noninteractive}

if [[ ! -f "$PREPARED_FLAG" ]]; then
  apt-get update -qq
  apt-get install -y -qq \
    curl \
    net-tools \
    iproute2 \
    lsof \
    procps \
    ca-certificates \
    gnupg2 || {
      echo "[metric-node] Failed to install base packages" >&2
      exit 1
    }

  mkdir -p "$(dirname "$PREPARED_FLAG")"
  touch "$PREPARED_FLAG"
fi

if [[ -n "${TZ:-}" ]]; then
  ln -snf "/usr/share/zoneinfo/${TZ}" /etc/localtime 2>/dev/null || true
  echo "$TZ" > /etc/timezone 2>/dev/null || true
fi

mkdir -p "$AGENT_ROOT"
chown -R "${ARGUS_BUILD_UID}:${ARGUS_BUILD_GID}" "$AGENT_ROOT" 2>/dev/null || true

if [[ "${METRIC_NODE_ROLE:-cpu}" == "gpu" ]]; then
  if ! command -v nvidia-smi >/dev/null 2>&1; then
    echo "[metric-node] nvidia-smi not available but GPU role requested" >&2
    exit 1
  fi
  nvidia-smi || true
fi

exec "$@"
