#!/bin/bash
SNMP_CONF="${SNMP_CONF:-/etc/snmp/snmp.conf}"
MIBDIRS_LINE='mibdirs /usr/share/snmp/mibs:/usr/share/snmp/mibs/iana:/usr/share/snmp/mibs/ietf'
DEFAULT_MIBDIRS_MARKER='/usr/share/snmp/mibs/iana:/usr/share/snmp/mibs/ietf'
# Ensure file exists
touch "$SNMP_CONF"
chmod 664 "$SNMP_CONF"

# Ensure file ends with a newline so appends don't concatenate
[[ -s "$SNMP_CONF" && $(tail -c1 "$SNMP_CONF" | wc -l) -eq 0 ]] && echo "" >> "$SNMP_CONF"

# Comment out "mibs :" if present and uncommented (empty MIB list; conflicts with tuning)
if grep -qE '^[[:space:]]*mibs[[:space:]]+:' "$SNMP_CONF"; then
	sed -i -E 's/^([[:space:]]*)(mibs[[:space:]]+:.*)$/# \1\2/' "$SNMP_CONF"
	echo "commented out mibs : in $SNMP_CONF"
fi

USE_MIBDIRS=false
if command -v net-snmp-config >/dev/null 2>&1; then
	default_mibdirs=$(net-snmp-config --default-mibdirs 2>/dev/null)
	if [[ -n "$default_mibdirs" ]] && echo "$default_mibdirs" | grep -qF "$DEFAULT_MIBDIRS_MARKER"; then
		USE_MIBDIRS=true
	fi
fi

if [[ "$USE_MIBDIRS" == true ]]; then
	if grep -qE '^\s*mibs\s+\+ALL' "$SNMP_CONF"; then
		sed -i -E 's/^([[:space:]]*)(mibs[[:space:]]+\+ALL.*)$/# \1\2/' "$SNMP_CONF"
		echo "commented out mibs +ALL in $SNMP_CONF (net-snmp default mibdirs include iana/ietf paths)"
	fi
	if grep '^[[:space:]]*mibdirs' "$SNMP_CONF" | grep -qF '/usr/share/snmp/mibs:/usr/share/snmp/mibs/iana:/usr/share/snmp/mibs/ietf'; then
		echo "mibdirs for iana/ietf layout already set in $SNMP_CONF, nothing to do."
	else
		echo "$MIBDIRS_LINE" >> "$SNMP_CONF"
		echo "added mibdirs directive to $SNMP_CONF"
	fi
# If we already have the mibs setting we want, do nothing
elif grep -qE '^\s*mibs\s+\+ALL' "$SNMP_CONF"; then
	echo "mibs +ALL already set in $SNMP_CONF, nothing to do."
# If a different mibs directive exists, comment it out and replace with the one we want
elif grep -qE '^\s*mibs\s+' "$SNMP_CONF"; then
	sed -i -E 's/^(\s*mibs\s+.*)/# \1\nmibs +ALL/' "$SNMP_CONF"
	echo "replacing mibs directive with mibs +ALL in $SNMP_CONF"
# Add the setting we want if we haven't already and it isn't there
else
	echo "mibs +ALL" >> "$SNMP_CONF"
	echo "added mibs +ALL directive to $SNMP_CONF"
fi

if grep -qE '^\s*mibWarningLevel\s+0' "$SNMP_CONF"; then
	echo "mibWarningLevel 0 already set in $SNMP_CONF, nothing to do."
elif grep -qE '^\s*mibWarningLevel\s+' "$SNMP_CONF"; then
	sed -i -E 's/^(\s*mibWarningLevel\s+.*)/# \1\nmibWarningLevel 0/' "$SNMP_CONF"
	echo "replacing mibWarningLevel directive with mibWarningLevel 0 in $SNMP_CONF"
else
	echo "mibWarningLevel 0" >> "$SNMP_CONF"
	echo "added mibWarningLevel 0 directive to $SNMP_CONF"
fi
