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

LOG_PREFIX="[NODE]"
RUNTIME_USER="argusagent"
RUNTIME_GROUP="argusagent"
AGENT_UID="${ARGUS_BUILD_UID:-2133}"
AGENT_GID="${ARGUS_BUILD_GID:-2015}"
HOSTNAME_VAL="${HOSTNAME:-unknown}"

log() { echo "${LOG_PREFIX} $*"; }

# Prepare runtime user
if ! getent group "$AGENT_GID" >/dev/null 2>&1; then
  groupadd -g "$AGENT_GID" "$RUNTIME_GROUP" || true
else
  RUNTIME_GROUP="$(getent group "$AGENT_GID" | cut -d: -f1)"
fi
if ! getent passwd "$AGENT_UID" >/dev/null 2>&1; then
  useradd -u "$AGENT_UID" -g "$AGENT_GID" -M -s /bin/bash "$RUNTIME_USER" || true
else
  RUNTIME_USER="$(getent passwd "$AGENT_UID" | cut -d: -f1)"
fi
log "runtime user: $RUNTIME_USER ($AGENT_UID:$AGENT_GID)"

# Ensure agent data dirs exist (host volumes mounted)
AGENT_DIR="/private/argus/agent/${HOSTNAME_VAL}"
HEALTH_DIR="${AGENT_DIR}/health"
mkdir -p "$HEALTH_DIR"
chown -R "$AGENT_UID:$AGENT_GID" "$AGENT_DIR" 2>/dev/null || true

# Stage Fluent Bit assets into /private to reuse existing startup script
mkdir -p /private
if [[ -f /assets/start-fluent-bit.sh ]]; then
  cp /assets/start-fluent-bit.sh /private/start-fluent-bit.sh
  chmod +x /private/start-fluent-bit.sh
fi
if [[ -d /assets/fluent-bit/etc ]]; then
  rm -rf /private/etc && mkdir -p /private
  cp -r /assets/fluent-bit/etc /private/
fi
if [[ -d /assets/fluent-bit/packages ]]; then
  cp -r /assets/fluent-bit/packages /private/
fi

# Start Fluent Bit in background (will block, so run via bash -lc &)
if [[ -x /private/start-fluent-bit.sh ]]; then
  log "starting fluent-bit"
  sysctl -w fs.inotify.max_user_instances=512 >/dev/null 2>&1 || true
  sysctl -w fs.inotify.max_user_watches=524288 >/dev/null 2>&1 || true
  bash -lc 'ulimit -n 65536 || true; exec /private/start-fluent-bit.sh' &
else
  log "missing /private/start-fluent-bit.sh; fluent-bit will not start"
fi

# Start agent in foreground as runtime user
log "starting argus-agent"
exec su -s /bin/bash -c /usr/local/bin/argus-agent "$RUNTIME_USER"
