#!/bin/sh

# PROVIDE: smartctl_exporter
# REQUIRE: LOGIN
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# smartctl_exporter_enable (bool):	Set to YES to enable smartctl_exporter, default is NO
# smartctl_exporter_user (string):	Set user to run as, default is root
# smartctl_exporter_syslog (bool):	Set to YES to use syslog, default is NO
#
# Use the following variables to override smartctl_exporter's defaults:
#
# smartctl_exporter_listen_address (string): 	Set address to listen on, default is localhost:9633
# smartctl_exporter_devices (string):		Space-separated list of devices (e.g., /dev/ada0 /dev/nvme0).
#						A device type can be appended after a semicolon
#						(e.g., "/dev/mfi0;megaraid,1").
#						If not set, smartctl_exporter auto-discovers devices.
# smartctl_exporter_device_exclude (string):	Regexp to exclude devices from auto-discovery, default is "nda"
#						to filter out NVMe CAM devices (use nvme controller instead).
# smartctl_exporter_log_level (string):		Only log messages with the given severity or above. One of: [debug, info, warn, error]
# smartctl_exporter_log_format (string):	Output format of log messages. One of: [logfmt, json]
# smartctl_exporter_args (string):		Extra arguments to pass to smartctl_exporter, default is empty

. /etc/rc.subr

name=smartctl_exporter
rcvar=smartctl_exporter_enable

load_rc_config $name

: ${smartctl_exporter_enable:="NO"}
: ${smartctl_exporter_user:="root"}
: ${smartctl_exporter_syslog:="NO"}
: ${smartctl_exporter_listen_address:="localhost:9633"}
: ${smartctl_exporter_devices:=""}
: ${smartctl_exporter_device_exclude:="nda"}
: ${smartctl_exporter_log_level:=""}
: ${smartctl_exporter_log_format:=""}

pidfile=/var/run/smartctl_exporter.pid
command=/usr/sbin/daemon

if checkyesno smartctl_exporter_syslog; then
	smartctl_exporter_syslog_args="-S"
fi

# The command line is passed to eval by rc.subr(8), so quote the values
# that may contain shell metacharacters.
for _diskdev in ${smartctl_exporter_devices}; do
	smartctl_exporter_device_args="${smartctl_exporter_device_args} --smartctl.device='${_diskdev}'"
done

command_args="-c -f -P ${pidfile} \
	${smartctl_exporter_user:+-u "${smartctl_exporter_user}"} \
	${smartctl_exporter_syslog_args} \
	${smartctl_exporter_daemon} \
	%%PREFIX%%/libexec/smartctl_exporter \
	${smartctl_exporter_listen_address:+--web.listen-address="${smartctl_exporter_listen_address}"} \
	${smartctl_exporter_device_args} \
	${smartctl_exporter_device_exclude:+--smartctl.device-exclude='${smartctl_exporter_device_exclude}'} \
	${smartctl_exporter_log_level:+--log.level="${smartctl_exporter_log_level}"} \
	${smartctl_exporter_log_format:+--log.format="${smartctl_exporter_log_format}"} \
	${smartctl_exporter_args}"

run_rc_command "$1"
