#!/bin/bash
set -eu

source "./custom/defines.sh"

# Make sure service is stopped
systemctl stop snmpd.service

# Create dynamic config directory if it doesn't exist
mkdir -p "${DYNAMIC_CONFIG_DIR}"

# Read restored JSON into variables without creating a file
json=$(setman-restore "snmpd" "settings.json")

isEnabled=$(jq -r '.isEnabled' <<< "$json")
sysLocation=$(jq -r '.sysLocation' <<< "$json")

# Check if syslocation exists
if grep -qE '^\s*syslocation' "${DYNAMIC_CONFIG_FILE}"; then
    # Replace only what comes after "syslocation"
    sed -i \
        "s|^\s*syslocation.*|syslocation ${sysLocation}|" \
        "${DYNAMIC_CONFIG_FILE}"
else
    # Append new syslocation at the end
    echo "syslocation ${sysLocation}" >> "${DYNAMIC_CONFIG_FILE}"
fi

# Restore SNMP user credentials file
mkdir -p "${SNMPD_USER_CRED_FILE_DIR}"
setman-restore "snmpd" "${SNMPD_USER_CRED_FILE_NAME}" > "${SNMPD_USER_CRED_FILE}"

# Enable or disable SNMP service according to JSON
if [ "$isEnabled" = "true" ]; then
    setman-log notice snmpd "Enabling SNMP service..."
    systemctl enable snmpd.service
    systemctl start --no-block snmpd.service
else
    setman-log notice snmpd "Disabling SNMP service..."
    systemctl disable snmpd.service
    systemctl stop --no-block snmpd.service
fi
