#!/sbin/openrc-run

name="Garage"
description="Lightweight S3-compatible distributed object store"

: ${cfgfile:="/etc/garage/garage.toml"}
: ${log_syslog="yes"}
: ${log_level="warn"}
: ${command_user:="garage"}

command="/usr/bin/garage"
command_args="-c $cfgfile server"
command_background="yes"

pidfile="/run/$RC_SVCNAME.pid"

required_files="$cfgfile"

depend() {
	need localmount net
	after firewall
}

start_pre() {
	export RUST_LOG=${RUST_LOG:-"netapp=$log_level,garage=$log_level"}

	yesno "$log_syslog" && export GARAGE_LOG_TO_SYSLOG=1

	local rpc_secret_file="$(sed -En 's/^rpc_secret_file\s*=\s*"([^"]+)"/\1/p' "$cfgfile")"
	if [ "$rpc_secret_file" ] && ! [ -f "$rpc_secret_file" ] ; then
		einfo "Generating $rpc_secret_file with a random key..."
		local pass="$(head /dev/urandom | tr -dc a-f0-9 | head -c 64)"
		( umask 077; echo "$pass" > "$rpc_secret_file" )
		chown "$command_user" "$rpc_secret_file"
	fi

	if [ "${error_log:-}" ]; then
		checkpath -f -m 640 -o "$command_user" "$error_log" || return 1
	fi
}
