#!/command/with-contenv bash

set -o errexit
set -o nounset
set -o pipefail
shopt -s inherit_errexit

ROMM_LOG_TAG="valkey"
# shellcheck source=SCRIPTDIR/../../scripts/lib.sh
source /etc/s6-overlay/scripts/lib.sh

record_process_group

if [[ -n ${REDIS_HOST:-} ]]; then
	info_log "REDIS_HOST is set, not starting internal valkey-server"
	disable_service
fi

info_log "Starting internal valkey"

# Snapshots rewrite hundreds of MB of rebuildable metadata, so take them hourly
# rather than valkey's every few minutes. An empty REDIS_SAVE_POLICY disables them.
REDIS_SAVE_POLICY="${REDIS_SAVE_POLICY="3600 1"}"

declare -a save_flags=(--save "")
if [[ -n ${REDIS_SAVE_POLICY} ]]; then
	# shellcheck disable=SC2206 # each "<seconds> <changes>" token is its own argument
	save_flags=(--save ${REDIS_SAVE_POLICY})
fi

# Valkey otherwise ignores SIGTERM when its exit snapshot can't be written (say,
# a read-only /redis-data), until s6 escalates to SIGKILL.
declare -a args=(--dir /redis-data "${save_flags[@]}" --shutdown-on-sigterm force)
if [[ -f /usr/local/etc/valkey/valkey.conf ]]; then
	args=(/usr/local/etc/valkey/valkey.conf --shutdown-on-sigterm force)
fi

if [[ ${LOGLEVEL^^} == "DEBUG" ]]; then
	exec valkey-server "${args[@]}"
fi
exec valkey-server "${args[@]}" >/dev/null 2>&1
