#!/usr/bin/env bash
#
# compile-mib-manager.sh
#
# Compiles the MibManager example against the SNMP4J-SMI-PRO "jar-with-
# dependencies" and the SNMP4J core library. The resulting MibManager.class
# is written next to MibManager.java (this script's directory).
#
# The SNMP4J-SMI-PRO jar and the SNMP4J core jar are discovered relative to
# this script. Both locations can be overridden with the environment variables
# SMI_PRO_JAR and SNMP4J_JAR respectively.
#
# SNMP4J-SMI-PRO
# ----------------------------------
# Copyright (C) 2012-2026 Frank Fock
#

set -euo pipefail

# Directory of this script (the "examples" directory) and the project root.
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
    # newest matching jar
    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
}

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

echo "Using SMI-PRO jar : $SMI_PRO_JAR_RESOLVED"

javac -cp "$SMI_PRO_JAR_RESOLVED" \
      -d "$SCRIPT_DIR" \
      "$SCRIPT_DIR/MibManager.java"

echo "Compiled: $SCRIPT_DIR/MibManager.class"
