#!/usr/bin/with-contenv bashio
# shellcheck shell=bash
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 "Museum: 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
    # We'll connect as DB_USER (the one we created), not postgres superuser
    DB_USER="$(bashio::config 'DB_USERNAME')"
    bashio::log.info "Museum: waiting for internal Postgres..."
    until pg_isready -q -h 127.0.0.1 -p 5432 -U "${DB_USER}"; do
        sleep 2
    done
fi

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