#!/bin/sh
#
# PROVIDE: graylog
# REQUIRE: NETWORKING SERVERS
# BEFORE: DAEMON
# KEYWORD: shutdown
#

# graylog_enable (bool):
#   Default value: "NO"
#   Flag that determines whether graylog is enabled
#
# graylog_user (username):
#   Default value: "graylog"
#   Name of the graylog user account
#
# graylog_group (group):
#   Default value: "graylog"
#   Name of the graylog group
#
# graylog_config (string)
#   Default value %%ETCDIR%%/graylog.conf
#   Path to the graylog configuration file
#
# graylog_min_mem (string):
#   Default value: 256m
#   Minumum JVM heap size
#
# graylog_max_mem (string):
#   Default value: 1g
#   Maximum JVM heap size
#
# graylog_dir (string):
#   Default value: %%DATADIR%%
#   Path to the graylog installation.
#
# graylog_data_dir (string):
#   Default vaule: %%GRAYLOG_DATA_DIR%%
#   Storage location for the graylog journal
#
# graylog_run_dir (string):
#   Default value: /var/graylog
#   Path to the graylog run folder.
#
# graylog_log_config (string):
#   Default value: %%ETCDIR%%/server/log4j2.xml
#   Path to the Graylog Server logfile
#
# graylog_java_home (path):
#   Default value: %%JAVA_HOME%%
#   Set it to the root of the JDK to use.

. /etc/rc.subr

name=graylog
rcvar=graylog_enable
load_rc_config $name

: ${graylog_enable:="NO"}
: ${graylog_config:="%%ETCDIR%%/graylog.conf"}
: ${graylog_data_dir:="%%GRAYLOG_DATA_DIR%%"}
: ${graylog_dir:="%%DATADIR%%"}
: ${graylog_group:="%%GRAYLOGGROUP%%"}
: ${graylog_java_home:="%%JAVA_HOME%%"}
: ${graylog_java_opts:=""}
: ${graylog_log_config:="%%ETCDIR%%/log4j2.xml"}
: ${graylog_logs_dir:="%%GRAYLOG_LOGS_DIR%%"}
: ${graylog_max_mem:="1g"}
: ${graylog_min_mem:="256m"}
: ${graylog_run_dir:="/var/run/graylog"}
: ${graylog_user:="%%GRAYLOGUSER%%"}

java_options=" \
    -Dapp=${name} \
    -Djava.awt.headless=true \
    -Dlog4j.configurationFile=${graylog_log_config} \
    -XX:+HeapDumpOnOutOfMemoryError \
    -XX:+ResizeTLAB \
    -XX:+UseCompressedOops \
    -XX:-OmitStackTraceInFastThrow \
    -XX:NewRatio=1 \
    -Xms${graylog_min_mem} \
    -Xmx${graylog_max_mem} \
    ${graylog_java_opts} \
    "

app_pidfile="${graylog_run_dir}/${name}.pid"
pidfile="${graylog_run_dir}/daemon.pid"
command="/usr/sbin/daemon"

command_args=" \
    -c \
    -t ${name} \
    -r \
    -p ${app_pidfile} \
    -P ${pidfile} \
    %%LOCALBASE%%/bin/java \
    ${java_options} \
    -jar ${graylog_dir}/graylog.jar server \
    --no-pid-file \
    --configfile ${graylog_config}"

export JAVA_HOME=${graylog_java_home}

required_files="%%LOCALBASE%%/bin/java ${graylog_config}"

graylog_precmd() {
    install -d -o ${graylog_user} -g ${graylog_group} -m 750 "${graylog_data_dir}"
    install -d -o ${graylog_user} -g ${graylog_group} -m 750 "${graylog_logs_dir}"
    install -d -o ${graylog_user} -g ${graylog_group} -m 750 "${graylog_run_dir}"
}

start_precmd="graylog_precmd"

run_rc_command "$1"
