#!/bin/sh

# PROVIDE: opensearch_dashboards
# REQUIRE: DAEMON
# BEFORE: LOGIN
# KEYWORD: shutdown

. /etc/rc.subr

name=opensearch_dashboards
rcvar=opensearch_dashboards_enable

load_rc_config $name

: ${opensearch_dashboards_enable:="NO"}
: ${opensearch_dashboards_config:="%%ETCDIR%%/opensearch_dashboards.yml"}
: ${opensearch_dashboards_user:="www"}
: ${opensearch_dashboards_group:="www"}
: ${opensearch_dashboards_log:="/var/log/opensearch_dashboards.log"}
: ${opensearch_dashboards_syslog_output_enable:="NO"}

start_precmd="opensearch_dashboards_start_precmd"
reload_cmd="opensearch_dashboards_reload_cmd"
extra_commands="reload"

if checkyesno opensearch_dashboards_syslog_output_enable; then
	if [ -n "${opensearch_dashboards_syslog_output_tag}" ]; then
		opensearch_dashboards_syslog_output_flags="-T ${opensearch_dashboards_syslog_output_tag}"
	else
		opensearch_dashboards_syslog_output_flags="-T ${name}"
	fi
	if [ -n "${opensearch_dashboards_syslog_output_priority}" ]; then
		opensearch_dashboards_syslog_output_flags="${opensearch_dashboards_syslog_output_flags} -s ${opensearch_dashboards_syslog_output_priority}"
	fi
	if [ -n "${opensearch_dashboards_syslog_output_facility}" ]; then
		opensearch_dashboards_syslog_output_flags="${opensearch_dashboards_syslog_output_flags} -l ${opensearch_dashboards_syslog_output_facility}"
	fi
fi

NODE="%%LOCALBASE%%/bin/node"

required_files="${opensearch_dashboards_config}"
pidfile="/var/run/${name}.pid"

command="/usr/sbin/daemon"
command_args="-f ${opensearch_dashboards_syslog_output_flags} -P ${pidfile} -t ${name} \
	/usr/bin/env NODE_ENV=production ${opensearch_dashboards_env} \
	${NODE} %%WWWDIR%%/src/cli/dist serve \
	--config ${opensearch_dashboards_config} --log-file ${opensearch_dashboards_log} \
	${opensearch_dashboards_args}"

opensearch_dashboards_start_precmd()
{
	if [ ! -e "${pidfile}" ]; then
		install -m 0600 -o ${opensearch_dashboards_user} -g ${opensearch_dashboards_group} /dev/null ${pidfile}
	fi
	if [ ! -f ${opensearch_dashboards_log} ]; then
		install -o ${opensearch_dashboards_user} -g ${opensearch_dashboards_group} -m 640 /dev/null ${opensearch_dashboards_log}
	fi
	if [ ! -d %%WWWDIR%%/optimize ]; then
		install -d -o ${opensearch_dashboards_user} -g ${opensearch_dashboards_group} %%WWWDIR%%/optimize
	else
		# We may have installed a plugin as root which will cause files in here
		# to be owned by root:wheel. Fix with a chown.
		chown -R ${opensearch_dashboards_user}:${opensearch_dashboards_group} %%WWWDIR%%/optimize
	fi
}

opensearch_dashboards_reload_cmd()
{
	if [ -z "$rc_pid" ]; then
		_run_rc_notrunning
		return 1
	else
		pkill -HUP -P ${rc_pid}
	fi
}

run_rc_command "$1"
