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

# --- Always work from the script's directory ---
cd "$(dirname "$0")" || exit 1

# --- Credentials file, stored alongside this script ---
CREDS_FILE="resxtop_creds"

if [[ ! -f "$CREDS_FILE" ]]; then
    echo "Credentials file '$CREDS_FILE' not found in $(pwd)!" >&2
    exit 1
fi

# Load ESXI_HOST, ESXI_USER, ESXI_PASS from the credentials file
# shellcheck disable=SC1090
source "$CREDS_FILE"

# Basic validation
if [[ -z "${ESXI_HOST:-}" || -z "${ESXI_USER:-}" || -z "${ESXI_PASS:-}" ]]; then
    echo "ERROR: ESXI_HOST, ESXI_USER, and/or ESXI_PASS not set in $CREDS_FILE" >&2
    exit 1
fi

# --- Environment required for resxtop ---
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH:-}:/usr/lib/vmware/resxtop"

# VMware-style environment
export VI_SERVER="$ESXI_HOST"
export VI_USERNAME="$ESXI_USER"
export VI_PASSWORD="$ESXI_PASS"

# --- Run resxtop in batch mode ---
# -b = CSV mode
# -d 1 = internal sampling delay (ignored because we use -n 1)
# -n 1 = ONE sample only (Telegraf controls how often this script runs)
#
# Output goes to STDOUT so Telegraf can parse it directly.
resxtop -b -d 1 -n 1
