#!/bin/sh

# PROVIDE: datadog_agent
# REQUIRE: LOGIN
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# datadog_agent_enable (bool):	Set to NO by default.
#				Set it to YES to enable Datadog Agent.
# datadog_agent_user (user):	Set user to run Datadog Agent.
#				Default is "datadog".
# datadog_agent_conf (path):	Path to Datadog Agent configuration file.
#				Default is /usr/local/etc/datadog

. /etc/rc.subr

name=datadog_agent
rcvar=datadog_agent_enable

load_rc_config $name

: ${datadog_agent_enable:="NO"}
: ${datadog_agent_user:="datadog"}
: ${datadog_agent_conf:="/usr/local/etc/datadog"}

command="/usr/local/bin/datadog-agent/agent"
command_args="-c ${datadog_agent_conf}"

required_files=/usr/local/etc/datadog/datadog.yaml
pidfile="/var/run/datadog/datadog-agent.pid"

extra_commands="status restart status configcheck check diagnose stats flare health help launch_gui secret version"

start_cmd="${name}_start"
stop_cmd="${name}_stop"
status_cmd="${name}_status"
restart_cmd="${name}_restart"
configcheck_cmd="${name}_command configcheck $@"
check_cmd="${name}_command check $@"
diagnose_cmd="${name}_command diagnose $@"
stats_cmd="${name}_command stats $@"
flare_cmd="${name}_command flare $@"
health_cmd="${name}_command health $@"
help_cmd="${name}_command help $@"
launch_gui_cmd="${name}_command launch-gui $@"
secret_cmd="${name}_command secret $@"
version_cmd="${name}_command version $@"

datadog_agent_status()
{
	rc_pid=`check_pidfile ${pidfile} ${command}`
	if [ -n "${rc_pid}" ]; then
		echo "Datadog agent is running as pid ${rc_pid}."
	else
		echo "Datadog agent is not running."
		return 1
	fi
}

datadog_agent_restart()
{
	datadog_agent_stop && datadog_agent_start
	return $?
}

datadog_agent_start() {
	/usr/sbin/daemon -f -p ${pidfile} -u ${datadog_agent_user} ${command} ${command_args} run
	return $?
}

datadog_agent_stop() {
	${command} ${command_args} stop
	return $?
}

datadog_agent_command() {
	${command} ${command_args} $1
	return $?
}

run_rc_command "$@"
