#!/sbin/openrc-run

# Upper case variables are here for backward compatibility.
: ${command_user:=${ZNC_USER:-"znc"}}
: ${datadir:=${ZNC_CONF:-"/var/lib/znc"}}

extra_started_commands="reload save"
extra_stopped_commands="setup"
description_reload="Reload ZNC configuration from disk"
description_save="Save ZNC configuration to disk"
description_setup="Interactively create a new config"

command="/usr/bin/znc"
command_args="-f -d $datadir ${command_args:-}"
command_background="yes"
pidfile="/run/$RC_SVCNAME.pid"

depend() {
	need net
}

start_pre() {
	if [ ! -f "$datadir"/configs/znc.conf ]; then
		eerror "File $datadir/configs/znc.conf does not exist!"
		eerror "Run 'rc-service $RC_SVCNAME setup' to create ZNC configuration."
		return 1
	fi
}

reload() {
	ebegin "Reloading ZNC configuration from disk"
	start-stop-daemon --signal SIGHUP --pidfile "$pidfile"
	eend $?
}

save() {
	ebegin "Saving ZNC configuration to disk"
	start-stop-daemon --signal SIGUSR1 --pidfile "$pidfile"
	eend $?
}

setup() {
	ebegin "Creating a new ZNC config"
	checkpath -d -m 750 -o "$command_user" "$datadir"
	su "$command_user" -s /bin/sh -c "$command $command_args --makeconf"
	eend $?
}
