#!/usr/bin/with-contenv bashio
set -euo pipefail

CFG=/config/museum.yaml
if ! bashio::fs.file_exists "$CFG"; then
    bashio::log.error "$CFG not found; aborting museum start."
    exit 1
fi

if bashio::config.true 'USE_EXTERNAL_DB'; then
    DB_HOST="$(bashio::config 'DB_HOSTNAME')"
    DB_PORT="$(bashio::config 'DB_PORT')"
    DB_USER="$(bashio::config 'DB_USERNAME')"
    bashio::log.info "Waiting for external Postgres at ${DB_HOST}:${DB_PORT}…"
    until pg_isready -q -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}"; do
        sleep 2
    done
else
    DB_USER="postgres"
    bashio::log.info "Waiting for internal Postgres…"
    until pg_isready -q -h localhost -p 5432 -U "${DB_USER}"; do
        sleep 2
    done
fi

bashio::log.info "Starting museum."
exec /usr/bin/museum --config "$CFG"
