#!/usr/bin/env bash
#
# mib-manager.sh
#
# Convenience launcher for the MibManager example. If MibManager.class does
# not yet exist, it is compiled first by calling compile-mib-manager.sh in the
# same directory. Afterwards the MibManager command line tool is executed with
# all parameters and options passed through to it.
#
# Examples:
#   ./mib-manager.sh help
#   ./mib-manager.sh repo create ./mibs ./mibrepository -L <license> <key>
#   ./mib-manager.sh repo create2pass ./mibs ./mibrepository -L <license> <key>
#   ./mib-manager.sh repo update ./mibs ./mibrepository
#   ./mib-manager.sh repo check ./mibrepository
#   ./mib-manager.sh repo remove IF-MIB -M ./mibrepository
#   ./mib-manager.sh mib find 1.3.6.1.2.1.1.1 -M ./mibrepository
#
# The SNMP4J-SMI-PRO jar and the SNMP4J core jar are discovered relative to
# this script and can be overridden with SMI_PRO_JAR and SNMP4J_JAR.
#
# SNMP4J-SMI-PRO
# ----------------------------------
# Copyright (C) 2012-2026 Frank Fock
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

# --- locate the SNMP4J-SMI-PRO jar-with-dependencies ----------------------
find_smi_pro_jar() {
    if [ -n "${SMI_PRO_JAR:-}" ] && [ -f "${SMI_PRO_JAR}" ]; then
        echo "$SMI_PRO_JAR"
        return 0
    fi
    local jar
    jar="$(ls -t "$PROJECT_DIR"/snmp4j-smi-pro-jar-with-dependencies.jar 2>/dev/null | head -n 1 || true)"
    if [ -n "$jar" ] && [ -f "$jar" ]; then
        echo "$jar"
        return 0
    fi
    return 1
}

# Compile on demand if the class file is missing.
if [ ! -f "$SCRIPT_DIR/MibManager.class" ]; then
    echo "MibManager.class not found, compiling ..." >&2
    "$SCRIPT_DIR/compile-mib-manager.sh"
fi

SMI_PRO_JAR_RESOLVED="$(find_smi_pro_jar || true)"
if [ -z "$SMI_PRO_JAR_RESOLVED" ]; then
    echo "ERROR: could not find the SNMP4J-SMI-PRO jar-with-dependencies." >&2
    echo "       Build the project (mvn package) or set SMI_PRO_JAR." >&2
    exit 1
fi

exec java -cp "$SMI_PRO_JAR_RESOLVED:$SCRIPT_DIR" MibManager "$@"
