#!/bin/sh
#
# PROVIDE: rmm_agent
# REQUIRE: NETWORKING
# KEYWORD: shutdown
#
# Add the following to /etc/rc.conf to enable:
#   rmm_agent_enable="YES"

. /etc/rc.subr

name="rmm_agent"
rcvar="rmm_agent_enable"

load_rc_config ${name}

: ${rmm_agent_enable:="NO"}
: ${rmm_agent_config:="/usr/local/rmm/config.yaml"}
: ${rmm_agent_logfile:="/var/log/rmm-agent.log"}
: ${rmm_agent_insecure:="YES"}

pidfile="/var/run/${name}.pid"
command="/usr/local/rmm/rmm-agent"

start_cmd="${name}_start"
stop_cmd="${name}_stop"
status_cmd="${name}_status"

rmm_agent_start()
{
    if [ ! -f "${command}" ]; then
        echo "rmm-agent binary not found: ${command}"
        return 1
    fi

    if [ ! -f "${rmm_agent_config}" ]; then
        echo "Config not found: ${rmm_agent_config}"
        return 1
    fi

    echo "Starting ${name}."

    INSECURE_FLAG=""
    if checkyesno rmm_agent_insecure; then
        INSECURE_FLAG="--insecure"
    fi

    /usr/sbin/daemon -f -p ${pidfile} -o ${rmm_agent_logfile} \
        ${command} --config ${rmm_agent_config} ${INSECURE_FLAG}
}

rmm_agent_stop()
{
    if [ -f "${pidfile}" ]; then
        echo "Stopping ${name}."
        kill $(cat ${pidfile}) 2>/dev/null
        rm -f ${pidfile}
    else
        echo "${name} is not running."
    fi
}

rmm_agent_status()
{
    if [ -f "${pidfile}" ] && kill -0 $(cat ${pidfile}) 2>/dev/null; then
        PID=$(cat ${pidfile})
        echo "${name} is running as pid ${PID}."
    else
        echo "${name} is not running."
        return 1
    fi
}

run_rc_command "$1"
