#!/bin/bash

#shellcheck disable=SC1091
source /usr/bin/xivo-upgrade-functions

refresh_collation() {
    local dbname="${1}"; shift

    docker exec xivocc-pgxivocc-1 psql -U postgres -qtAc "ALTER DATABASE ${dbname} REFRESH COLLATION VERSION"
}

get_databases() {
    docker exec xivocc-pgxivocc-1 psql -U postgres -qtAc "SELECT datname FROM pg_database;"
}

refresh_collation_after_upgrade() {
    wait_for_postgres "xivocc" "localhost" "5443" "postgres" "postgres"
    databases=$(get_databases)

    for db in ${databases}; do
        echo "Refreshing collation for db: ${db}"
        refresh_collation "${db}"
    done
}

check_used_postgres "xivocc"
if [[ "$USE_DB" == true ]]; then
    refresh_collation_after_upgrade
fi
