#!/sbin/openrc-run

extra_started_commands="reload reopen"
description_reload="Reload configuration file"
description_reopen="Reopen log file"

instance_name="${RC_SVCNAME#*.}"
instance_name="${instance_name:-stunnel}"

: ${cfgfile:=${STUNNEL_CONFIGFILE:-"/etc/stunnel/$instance_name.conf"}}

command="/usr/bin/stunnel"
command_args="$cfgfile $STUNNEL_OPTIONS $command_args"
pidfile="/run/stunnel/$instance_name.pid"  # default value

required_files="$cfgfile"


depend() {
	need net
	before logger
}

start_pre() {
	pidfile=$(config_get "pid" "$pidfile")

	local chroot_dir=$(config_get "chroot")
	[ -z "$chroot_dir" ] || start_stop_daemon_args="--chroot $chroot_dir"

	local user=$(config_get "setuid" "stunnel")
	local group=$(config_get "setgid" "stunnel")

	checkpath -d -m 0775 -o root:$group /run/stunnel

	if [ ! "$(dirname "$pidfile")" -ef "/run" ]; then
		checkpath -d -m 0755 -o $user:$group "$(dirname "$pidfile")"
	fi
}

stop_pre() {
	pidfile=$(config_get "pid" "$pidfile")
}

reload() {
	pidfile=$(config_get "pid" "$pidfile")

	ebegin "Reloading $RC_SVCNAME configuration"
	start-stop-daemon --signal HUP --pidfile "$pidfile" --name stunnel
	eend $?
}

reopen() {
	pidfile=$(config_get "pid" "$pidfile")

	ebegin "Reopening $RC_SVCNAME log file"
	start-stop-daemon --signal USR1 --pidfile "$pidfile" --name stunnel
	eend $?
}

config_get() {
	local key="$1"
	local default="${2:-}"

	local val="$(sed -En "s|^$key\s*=\s*(.*)\s*$|\1|p" "$cfgfile")"
	echo "${val:-$default}"
}
