#!/command/with-contenv /usr/bin/bash
# shellcheck shell=bash
# vim: set ft=bash ts=4 sw=4 sts=4 et :

set -euo pipefail

declare -r LOG_PREFIX="[init-db-wait]"

declare -ri TIMEOUT=60
declare -i ATTEMPT=0
declare -i DELAY=0
declare -i STARTED_AT=${EPOCHSECONDS:?EPOCHSECONDS var unset}

delay_next_attempt() {
	local -i elapsed=$(( EPOCHSECONDS - STARTED_AT ))
	local -ri remaining=$(( TIMEOUT - elapsed ))

	if (( remaining <= 0 )); then
		echo "${LOG_PREFIX} Unable to connect after $elapsed seconds."
		exit 1
	fi

	DELAY+=1

	# clamp to remaining time
	if (( DELAY > remaining )); then
		DELAY=$remaining
	fi

	ATTEMPT+=1
	echo "${LOG_PREFIX} Attempt $ATTEMPT failed! Trying again in $DELAY seconds..."
	sleep "$DELAY"
}

wait_for_postgres() {
	echo "${LOG_PREFIX} Waiting for PostgreSQL to start..."

	local -r host="${PAPERLESS_DBHOST:-localhost}"
	local -r port="${PAPERLESS_DBPORT:-5432}"
	local -r user="${PAPERLESS_DBUSER:-paperless}"

	while ! pg_isready -h "${host}" -p "${port}" --username "${user}"; do
		delay_next_attempt
	done
	echo "${LOG_PREFIX} Connected to PostgreSQL"
}

wait_for_mariadb() {
	echo "${LOG_PREFIX} Waiting for MariaDB to start..."

	local -r host="${PAPERLESS_DBHOST:-localhost}"
	local -r port="${PAPERLESS_DBPORT:-3306}"

	while ! mariadb-admin --host="${host}" --port="${port}" --skip-ssl ping --silent >/dev/null 2>&1; do
		delay_next_attempt
	done
	echo "${LOG_PREFIX} Connected to MariaDB"
}

if [[ "${PAPERLESS_DBENGINE:-}" == "mariadb" ]]; then
	wait_for_mariadb
elif [[ -n "${PAPERLESS_DBHOST:-}" ]]; then
	wait_for_postgres
fi

echo "${LOG_PREFIX} Database is ready"
