#!/sbin/openrc-run

name="stalwart-mail"
description="Stalwart mail server"
supervisor="supervise-daemon"
command="/usr/bin/stalwart"
command_user="${command_user:-stalwart:stalwart}"
command_args_foreground="--config $CONF_DIR/config.json"
capabilities="^cap_net_bind_service"

depend() {
	need localmount net
	after firewall
	before provide mta
}

start_pre() {
	checkpath -m 0755 -d -o "$command_user" "$DATA_DIR"
	checkpath -m 0755 -d -o "$command_user" "$CONF_DIR"
	checkpath -m 0755 -d -o "$command_user" "$LOG_DIR"

	# Ensure that all files belong to the stalwart user.
	# The bootstraping process below might be ran as root
	# or as a different user, so this ensures that the files
	# have the correct ownership.
	chown -R stalwart: $DATA_DIR $LOG_DIR $CONF_DIR

	# If the configuration file does not exist, start the service
	# in the foreground in order to display the bootstrap
	# instructions to the user. Once the bootstrap is completed,
	# the service will be restarted in the background.
	if [ ! -f "$CONF_DIR"/config.json ]; then
		stalwart $command_args_foreground
	fi
}
