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

HELPER_DIR="/usr/local/nagiosxi/var/nagios/xihelper"
VENV_DIR="$HELPER_DIR/venv"
BUNDLE_URL="https://assets.nagios.com/downloads/nagiosxi/misc/xihelper.tar.gz"
LOG="$HELPER_DIR/install.log"

STATUS_FILE="$HELPER_DIR/xihelper.install.status"
LOCK_FILE="$HELPER_DIR/xihelper.install.lock"

touch "$LOG"

exec 9>"$LOCK_FILE" || exit 1

if ! flock -n 9; then
  echo "running" > "$STATUS_FILE"
  exit 0
fi

echo "running" > "$STATUS_FILE"

cleanup() {
  rm -f "$LOCK_FILE"
}
trap cleanup EXIT
trap 'echo "error" > "$STATUS_FILE"' ERR

exec > >(tee -a "$LOG") 2>&1

echo "=== Nagios XI Helper install started ==="

PYTHON_BIN=python3

if command -v apt >/dev/null 2>&1; then
  apt-get update -y
  apt-get install -y python3 python3-pip curl tar build-essential

  if ! python3 -Im ensurepip --version >/dev/null 2>&1; then
    PY_VER=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
    apt-get install -y "python${PY_VER}-venv"
  fi

  PYTHON_BIN=python3
fi

if command -v dnf >/dev/null 2>&1; then
  dnf install -y curl tar gcc python3 python3-pip

  if grep -qE 'release 8' /etc/redhat-release 2>/dev/null; then
  if ! command -v python3.9 >/dev/null 2>&1; then
    dnf install -y python39 python39-pip
  fi
  PYTHON_BIN=python3.9
  fi

fi

echo "Using Python: $($PYTHON_BIN --version)"

cd "$HELPER_DIR"

curl -fsSL "$BUNDLE_URL" -o xihelper.tar.gz
tar -xzf xihelper.tar.gz
rm -f xihelper.tar.gz

rm -rf "$VENV_DIR"

"$PYTHON_BIN" -m venv "$VENV_DIR"

"$VENV_DIR/bin/pip" install \
  --upgrade \
  --no-cache-dir \
  pip setuptools wheel

"$VENV_DIR/bin/pip" install \
  --no-cache-dir \
  -r "$HELPER_DIR/requirements.txt"

"$VENV_DIR/bin/python" - <<'EOF'
import numpy, sklearn, joblib, onnxruntime, transformers
print("All dependencies OK")
EOF

echo "=== Nagios XI Helper install completed successfully ==="

echo "success" > "$STATUS_FILE"
