#!/bin/sh

# PROVIDE: restserver
# REQUIRE: DAEMON
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# restserver_enable (bool):	Set it to YES to enable restserver.
#			Default is "NO".
# restserver_user (user):	Set user to run restserver.
#			Default is "restserver".
# restserver_group (group):	Set group to run restserver.
#			Default is "restserver".
# restserver_store (dir):	Set restserver config file.
#			Default is "/var/db/restserver".
# restserver_syslog_output_enable (bool):	Set to enable syslog output.
#					Default is "NO". See daemon(8).
# restserver_syslog_output_priority (str):	Set syslog priority if syslog enabled.
#					Default is "info". See daemon(8).
# restserver_syslog_output_facility (str):	Set syslog facility if syslog enabled.
#					Default is "daemon". See daemon(8).

. /etc/rc.subr

name=restserver
rcvar=restserver_enable
desc="network API server for sysutils/restic backup software"

load_rc_config $name

: ${restserver_enable:="NO"}
: ${restserver_user:="restserver"}
: ${restserver_group:="restserver"}
: ${restserver_store:="/var/db/restserver"}
: ${restserver_options:="--listen 127.0.0.1:8000 --no-auth"}

DAEMON=$(/usr/sbin/daemon 2>&1 | grep -q syslog ; echo $?)
if [ ${DAEMON} -eq 0 ]; then
        : ${restserver_syslog_output_enable:="NO"}
        : ${restserver_syslog_output_priority:="info"}
        : ${restserver_syslog_output_facility:="daemon"}
        if checkyesno restserver_syslog_output_enable; then
                restserver_syslog_output_flags="-t ${name} -T ${name}"

                if [ -n "${restserver_syslog_output_priority}" ]; then
                        restserver_syslog_output_flags="${restserver_syslog_output_flags} -s ${restserver_syslog_output_priority}"
                fi

                if [ -n "${restserver_syslog_output_facility}" ]; then
                        restserver_syslog_output_flags="${restserver_syslog_output_flags} -l ${restserver_syslog_output_facility}"
                fi
        fi
else
        restserver_syslog_output_enable="NO"
        restserver_syslog_output_flags=""
fi

pidfile=/var/run/restserver.pid
procname="%%PREFIX%%/bin/rest-server"
command="/usr/sbin/daemon"
command_args="-f ${restserver_syslog_output_flags} -p ${pidfile} -t ${name} /usr/bin/env ${restserver_env} ${procname} --path ${restserver_store} ${restserver_options}"

extra_commands="reload monitor"
monitor_cmd=restserver_monitor
start_precmd=restserver_startprecmd
required_files="$restserver_config"

restserver_monitor()
{
	sig_reload=USR1
	run_rc_command "reload"
}

restserver_startprecmd()
{
        if [ ! -e ${pidfile} ]; then
                install -o ${restserver_user} -g ${restserver_group} /dev/null ${pidfile};
        fi

        if [ ! -d ${restserver_dir} ]; then
                install -d -o ${restserver_user} -g ${restserver_group} ${restserver_dir}
        fi
}

run_rc_command "$1"
