#!/sbin/openrc-run

name="pgpool-II"

: ${command_user:="postgres:postgres"}
: ${config_file:="/etc/pgpool/pgpool.conf"}
: ${hba_file:="/etc/pgpool/pool_hba.conf"}
: ${pcp_file:="/etc/pgpool/pcp.conf"}
: ${start_wait:=2}

command="/usr/bin/pgpool"
command_args="
	--dont-detach
	--config-file $config_file
	--hba-file $hba_file
	--pcp-file $pcp_file
	$command_args
	"
command_background="yes"
pidfile="/run/$RC_SVCNAME.pid"

start_stop_daemon_args="--wait $start_wait"
# The leading space is to avoid fallback to $start_stop_daemon_args when this
# is empty (supervise-daemon doesn't support --wait).
supervise_daemon_args=" $supervise_daemon_args"

required_files="$config_file"

# pgpool logs to stderr; send it to syslog unless $logfile is set.
if [ "$logfile" ]; then
	error_log="$logfile"
else
	: ${error_logger="logger -t $RC_SVCNAME -p local0.err >/dev/null 2>&1"}
fi

depend() {
	need net
	after firewall
	use logger postgresql
}

start_pre() {
	if [ -z "$key_file" ]; then
		key_file="/etc/pgpool/pool.key"

		# Backward compatibility with the former default.
		if ! [ -e "$key_file" ] && [ -e /etc/pgpool/pool_key ]; then
			ewarn "Using deprecated key file /etc/pgpool/pool_key, please rename it to pool.key"
			ewarn "or set key_file=\"/etc/pgpool/pool_key\" in /etc/conf.d/$RC_SVCNAME"
			key_file="/etc/pgpool/pool_key"
		fi
	fi
	command_args="--key-file $key_file $command_args"

	# The default pid_file_name. pgpool writes the pid file even with
	# --dont-detach and fails to start if its directory is missing. >_<
	checkpath -d -m 0750 -o "$command_user" /run/pgpool || return 1
	# The default unix_socket_directories. The same as in postgresql's init script.
	checkpath -d -m 1775 -o "$command_user" /run/postgresql
}
