#!/bin/sh

# PROVIDE: alloy
# REQUIRE: LOGIN
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# alloy_enable (bool):          Set to NO by default.
#               Set it to YES to enable alloy.
# alloy_user (string):          Set user that alloy will run under
#               Default is "nobody".
# alloy_group (string):         Set group that alloy will run under
#               Default is "nobody".
# alloy_listen_address (string):Set ip:port that alloy will listen on
#               Default is ":9200".
# alloy_storage_path (string):  Set storage.path
#               Default is "/var/alloy".
# alloy_args (string):          Set extra arguments to pass to alloy
#               Default is "".
# alloy_sig_stop (string):      Signal used to stop alloy. Default "TERM".
# alloy_stop_timeout (int):     Seconds to wait for graceful stop before SIGKILL.
#               Default is unset (rc.subr default wait). Set e.g. 30 for a timeout.

. /etc/rc.subr

name=alloy
rcvar=alloy_enable

load_rc_config $name

: ${alloy_enable:="NO"}
: ${alloy_user:="nobody"}
: ${alloy_group:="nobody"}
: ${alloy_args:=""}
: ${alloy_storage_path:="/var/alloy"}
: ${alloy_listen_address:=":9200"}
: ${alloy_sig_stop:="TERM"}
: ${alloy_stop_timeout:=}

pidfile=/var/run/alloy.pid
command="/usr/sbin/daemon"
procname="/usr/local/bin/alloy"
run="run /usr/local/etc/alloy.flow"
command_args="-f -S -T ${name} -p ${pidfile} /usr/bin/env ${procname} ${run} \
    --storage.path=${alloy_storage_path} --server.http.listen-addr=${alloy_listen_address} ${alloy_args}"

# Alloy reloads config on SIGHUP (see /-/reload and internal/alloycli/cmd_run.go).
sig_stop="${alloy_sig_stop}"
sig_reload="HUP"
extra_commands="reload"

start_precmd=alloy_startprecmd
stop_postcmd=alloy_stoppostcmd
[ -n "${alloy_stop_timeout}" ] && stop_cmd="alloy_stop"

alloy_startprecmd() {
  if [ ! -e ${pidfile} ]; then
    install -o ${alloy_user} -g ${alloy_group} /dev/null ${pidfile}
  fi
}

alloy_stoppostcmd() {
  rm -f ${pidfile}
}

alloy_stop() {
  rc_pid=$(check_pidfile "${pidfile}" "${procname}")
  if [ -z "${rc_pid}" ]; then
    return 0
  fi
  echo "Stopping ${name}."
  kill -${sig_stop} "${rc_pid}"
  wait_for_pids "${pidfile}" ${alloy_stop_timeout}
  kill -KILL "${rc_pid}" 2>/dev/null && echo "Killed."
  rm -f "${pidfile}"
}

load_rc_config $name
run_rc_command "$1"
