#!/bin/sh
# initMAX install-time Zabbix frontend version guard for navigatormax.
# Blocks install on a frontend older than the minimum this build
# supports; only warns when newer-than-tested or undetectable. No
# 'set -e' - a stray non-zero must not abort the install, only the
# explicit 'exit 1' below does.
MIN="6.0"
MAX="8.0"
WIDGET="navigatormax"

# Encode X.Y(.Z) as a comparable integer (minor zero-padded to 3).
ver_num() { echo "$1" | awk -F. '{printf "%d%03d\n", $1, ($2==""?0:$2)}'; }

# defines.inc.php carries  define('ZABBIX_VERSION', 'X.Y.Z');
CANDIDATES="/usr/share/zabbix/include/defines.inc.php
/usr/share/zabbix/ui/include/defines.inc.php
/usr/share/zabbix/php/include/defines.inc.php"
[ -n "$ZABBIX_FRONTEND_DIR" ] && CANDIDATES="$ZABBIX_FRONTEND_DIR/include/defines.inc.php $CANDIDATES"
DEFINES=""
for c in $CANDIDATES; do [ -f "$c" ] && { DEFINES="$c"; break; }; done

if [ -z "$DEFINES" ]; then
  echo "initMAX $WIDGET: Zabbix frontend not found (set ZABBIX_FRONTEND_DIR if non-standard) - skipping version check." >&2
  exit 0
fi

FE=$(grep -m1 ZABBIX_VERSION "$DEFINES" 2>/dev/null | grep -oE "[0-9]+\.[0-9]+(\.[0-9]+)?" | head -1)
if [ -z "$FE" ]; then
  echo "initMAX $WIDGET: could not read ZABBIX_VERSION from $DEFINES - skipping version check." >&2
  exit 0
fi

if [ "$(ver_num "$FE")" -lt "$(ver_num "$MIN")" ]; then
  echo "ERROR: initMAX $WIDGET requires Zabbix frontend >= $MIN, but $FE is installed ($DEFINES)." >&2
  echo "       Upgrade the Zabbix frontend, or install a widget build that supports $FE." >&2
  exit 1
fi

if [ -n "$MAX" ] && [ "$(ver_num "$FE")" -gt "$(ver_num "$MAX")" ]; then
  echo "WARNING: initMAX $WIDGET was tested up to Zabbix $MAX; detected $FE (newer). It should work but is unverified." >&2
fi

exit 0
