#!/sbin/openrc-run
# SPDX-License-Identifier: GPL-3.0-or-later

# The user netdata is configured to run as.
# If you edit its configuration file to set a different
# user, set it here too, to have its files switch ownership
: "${NETDATA_OWNER:=netdata:netdata}"

# The timeout in seconds to wait for netdata
# to save its database on disk and exit.
: "${NETDATA_WAIT_EXIT_TIMEOUT:=60}"

# When set to 1, if netdata does not exit in
# NETDATA_WAIT_EXIT_TIMEOUT, we will force it
# to exit.
: "${NETDATA_FORCE_EXIT:=0}"

# Netdata will use these services, only if they
# are enabled to start.
: "${NETDATA_START_AFTER_SERVICES:=apache2 squid nginx mysql named opensips upsd hostapd postfix lm_sensors}"

extra_started_commands="reload rotate save"
pidfile="@localstatedir_POST@/run/netdata/netdata.pid"
command="@sbindir_POST@/netdata"
command_args="-P ${pidfile} ${NETDATA_EXTRA_ARGS}"
start_stop_daemon_args="-u ${NETDATA_OWNER}"
required_files="/etc/netdata/netdata.conf"
if [ "${NETDATA_FORCE_EXIT}" -eq 1 ]; then
    retry="TERM/${NETDATA_WAIT_EXIT_TIMEOUT}/KILL/1"
else
    retry="TERM/${NETDATA_WAIT_EXIT_TIMEOUT}"
fi

depend() {
    use logger
    need net
    after ${NETDATA_START_AFTER_SERVICES}
}

start_pre() {
    checkpath -o ${NETDATA_OWNER} -d @localstatedir_POST@/cache/netdata @localstatedir_POST@/run/netdata
}

reload() {
    ebegin "Reloading Netdata"
    start-stop-daemon --signal SIGUSR2 --pidfile "${pidfile}"
    eend $? "Failed to reload Netdata"
}

rotate() {
    ebegin "Logrotating Netdata"
    start-stop-daemon --signal SIGHUP --pidfile "${pidfile}"
    eend $? "Failed to logrotate Netdata"
}

save() {
    ebegin "Saving Netdata database"
    start-stop-daemon --signal SIGUSR1 --pidfile "${pidfile}"
    eend $? "Failed to save Netdata database"
}
