#!/bin/sh
# RMM Agent — generate config and manage service

CONFIGDIR="/usr/local/rmm"
CONFIGFILE="${CONFIGDIR}/config.yaml"
# Generate config from model
mkdir -p "${CONFIGDIR}"
/usr/local/bin/php /usr/local/opnsense/scripts/OPNsense/RMMAgent/generate_config.php > "${CONFIGFILE}"

# Check if enabled
ENABLED=$(/usr/local/sbin/pluginctl -g OPNsense.rmmagent.general.Enabled 2>/dev/null)

# Check insecure flag
INSECURE=$(/usr/local/sbin/pluginctl -g OPNsense.rmmagent.general.Insecure 2>/dev/null)
if [ "${INSECURE}" = "1" ]; then
    /usr/sbin/sysrc rmm_agent_insecure="YES" > /dev/null 2>&1
else
    /usr/sbin/sysrc rmm_agent_insecure="NO" > /dev/null 2>&1
fi

if [ "${ENABLED}" = "1" ]; then
    /usr/sbin/sysrc rmm_agent_enable="YES" > /dev/null 2>&1
    /usr/local/etc/rc.d/rmm_agent restart
    echo "RMM Agent started"
else
    /usr/local/etc/rc.d/rmm_agent stop 2>/dev/null
    /usr/sbin/sysrc rmm_agent_enable="NO" > /dev/null 2>&1
    echo "RMM Agent stopped"
fi
