#!/bin/sh

# PROVIDE: clickhouse
# REQUIRE: LOGIN
# KEYWORD: shutdown
#
# Add the following line to /etc/rc.conf[.local] to enable clickhouse server
#
# clickhouse_enable (bool):  Set to "NO" by default
#                          Set it to "YES" to enable clickhouse server
%%LEGACY_LIMITS%%# clickhouse_limits (bool):  Set to "NO" by default.
%%LEGACY_LIMITS%%#                        Set it to yes to run `limits -e -U clickhouse`
%%LEGACY_LIMITS%%#                        just before clickhouse starts.
# clickhouse_config (str): Path to config file (required).
#                          (default: %%PREFIX%%/etc/clickhouse-server/config.xml)
# clickhouse_rundir (str):   Path to directory holding a pidfile.
#                          (default: /var/run/clickhouse)
# clickhouse_user (str):     User to run as
#                          (default: clickhouse)
# clickhouse_group (str):    Group to run as
#                          (default: clickhouse)
# clickhouse_logdir (str):   Path to log directory
#                          (default: /var/log/clickhouse)
# clickhouse_dbdir (str):    Path to world database directory
#                          (default: /var/db/clickhouse)

. /etc/rc.subr

name=clickhouse
rcvar=clickhouse_enable

load_rc_config ${name}

: ${clickhouse_enable="NO"}
%%LEGACY_LIMITS%%: ${clickhouse_limits="NO"}
: ${clickhouse_config="%%PREFIX%%/etc/clickhouse-server/config.xml"}
: ${clickhouse_rundir="/var/run/clickhouse"}
: ${clickhouse_user="clickhouse"}
: ${clickhouse_group="clickhouse"}
: ${clickhouse_logdir="/var/log/clickhouse"}
: ${clickhouse_dbdir="/var/db/clickhouse"}
: ${clickhouse_flags=""}
: ${clickhouse_pidfile="${clickhouse_rundir}/clickhouse.pid"}
: ${clickhouse_args="--server --daemon --pid-file ${clickhouse_pidfile} --config-file ${clickhouse_config} ${clickhouse_flags}"}

command=%%PREFIX%%/bin/clickhouse
pidfile=${clickhouse_pidfile}
command_args=${clickhouse_args}
required_files=${clickhouse_config}
start_precmd=clickhouse_prestart

clickhouse_prestart () {
	for _dir in ${clickhouse_rundir} ${clickhouse_logdir} ${clickhouse_dbdir}; do
		install -d -o ${clickhouse_user} -g ${clickhouse_group} ${_dir}
	done

%%LEGACY_LIMITS%%	if checkyesno clickhouse_limits; then
%%LEGACY_LIMITS%%		eval `/usr/bin/limits -e -U ${clickhouse_user}` 2>/dev/null
%%LEGACY_LIMITS%%	else
%%LEGACY_LIMITS%%		return 0
%%LEGACY_LIMITS%%	fi
%%MODERN_LIMITS%%	return 0
}

run_rc_command "$1"
