#!/sbin/openrc-run

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

: ${cfgfile:="/etc/$RC_SVCNAME.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"

_rpc_secret_placeholder='rpc_secret = "change-me"'

depend() {
	need localmount net
	after firewall
}

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

	# NOTE: Logging to syslog is not supported by upstream (yet), this is
	#  done by Alpine's patch for now.
	yesno "$log_syslog" && export GARAGE_SYSLOG=1

	if ! [ -f "$cfgfile.apk-new" ] && grep -qFx "$_rpc_secret_placeholder" "$cfgfile"; then
		if [ -w "$cfgfile" ]; then
			einfo "Replacing rpc_secret in $cfgfile with a random string..."

			local pass=$(head /dev/urandom | tr -dc a-f0-9 | head -c 64)
			sed -i "s/^$_rpc_secret_placeholder/rpc_secret = \"$pass\"/" "$cfgfile"
		else
			ewarn "Change rpc_secret in $cfgfile to a random password!"
		fi
	fi
	if [ "${error_log:-}" ]; then
		checkpath -f -m 640 -o "$command_user" "$error_log" || return 1
	fi
}
