#!/sbin/openrc-run

name="Meilisearch"
description="A lightning-fast search engine"

: ${command_user:="meilisearch"}
: ${datadir:="/var/lib/meilisearch"}
: ${start_wait:=50}  # milliseconds
: ${healthcheck_timer:=30}
: ${respawn_delay:=5}

command="/usr/bin/meilisearch"
command_background="yes"
directory="$datadir"
pidfile="/run/$RC_SVCNAME.pid"

start_stop_daemon_args="--wait $start_wait $start_stop_daemon_args"
# 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"

depend() {
	need localmount net
	after firewall
}

start_pre() {
	# Replace MEILI_MASTER_KEY placeholder with a random string.
	if [ "${MEILI_ENV:-}" = 'production' ] && [ "${MEILI_MASTER_KEY:-}" = 'change-me' ]; then
		local conf
		for conf in "/etc/conf.d/${RC_SVCNAME%%.*}" "/etc/conf.d/$RC_SVCNAME" ""; do
			[ -w "$conf" ] && break
		done
		if [ "$conf" ]; then
			einfo "Replacing MEILI_MASTER_KEY in $conf with a random string..."
			local pass=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 32)
			sed -Ei 's/^(MEILI_MASTER_KEY)="change-me"/\1="'"$pass"'"/' "$conf"

		else  # no writable config found
			ewarn "Change MEILI_MASTER_KEY in /etc/conf.d/ to a random alphanumeric string!"
		fi
	fi
	if [ "${logfile:-}" ]; then
		error_log="$logfile"
		checkpath -f -m 640 -o "$command_user" "$logfile" || return 1
	fi

	return 0
}

healthcheck() {
	[ "${MEILI_HTTP_ADDR:-}" ] || return 0
	[ -x /usr/bin/curl ] || return 0

	/usr/bin/curl -fq "$MEILI_HTTP_ADDR"/health
}
