#!/bin/sh

# PROVIDE: graphiteapi
# REQUIRE: LOGIN DAEMON NETWORKING
# KEYWORD: shutdown

# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# graphiteapi_enable    (bool):   Set to NO by default.
# Set it to YES to enable graphiteapi.
#
# graphiteapi_user      (string): optional username to run daemon under
# graphiteapi_group     (string): optional groupname to run daemon under
# graphiteapi_address   (string): optional IP:PORT tuple to bind to
# graphiteapi_config    (string): optional full path for yaml config file
# graphiteapi_flags     (string): optional flags to pass through to gunicorn

. /etc/rc.subr

name="graphiteapi"
rcvar="graphiteapi_enable"
desc="graphite-web rendering API"

load_rc_config ${name}

: ${graphiteapi_enable:="NO"}
: ${graphiteapi_user="carbon"}
: ${graphiteapi_group="carbon"}
: ${graphiteapi_address="127.0.0.1:5600"}
: ${graphiteapi_config="/usr/local/etc/graphite-api/graphiteapi.yaml"}
: ${graphiteapi_flags="--workers 4"}

required_files="${graphiteapi_config}"

command="/usr/local/bin/gunicorn-3.11"
procname="python3.11"

pidfile="/var/run/graphiteapi/graphiteapi.pid"

command_args="--daemon graphite_api.app:app"
command_args="${command_args} --user ${graphiteapi_user} --group ${graphiteapi_group}"
command_args="${command_args} --bind ${graphiteapi_address}"
command_args="${command_args} --env GRAPHITE_API_CONFIG=${graphiteapi_config}"
command_args="${command_args} --pid /var/run/graphiteapi/graphiteapi.pid"
command_args="${command_args} --worker-tmp-dir /var/run/graphiteapi"
command_args="${command_args} --error-logfile /var/log/graphiteapi/error.log"
command_args="${command_args} --access-logfile /var/log/graphiteapi/access.log"

extra_commands="reload"
start_precmd="start_precmd"

start_precmd()
{
    test -d "/var/log/graphiteapi" || install -d -o ${graphiteapi_user} \
        -g ${graphiteapi_group} -m 0750 "/var/log/graphiteapi"
    test -d "/var/run/graphiteapi" || install -d -o ${graphiteapi_user} \
        -g ${graphiteapi_group} -m 0750 "/var/run/graphiteapi"
}

run_rc_command "$1"
