#!/usr/bin/env bash
set -euo pipefail

echo "Refresh collation starting"

PSQL_COMMAND="psql -U $POSTGRES_USER"
DATABASES=$($PSQL_COMMAND -d postgres --no-align --tuples-only --command "select datname from PG_database;")

echo "Found the following DBs: \n $DATABASES"

for db in $DATABASES; do echo "Refreshing $db" && $PSQL_COMMAND -c "ALTER DATABASE \"$db\" REFRESH COLLATION VERSION;" && echo "Refreshed $db"; done;

echo "Refresh collation finished"

# Can be invoked on stores like:
# balena-run.sh command --devices k2-statecollege postgres 'apt update && apt install -qy wget && wget -O refresh-collation.sh https://copyparty.bcstuff.io/store-scripts/refresh-collation.sh && chmod +x ./refresh-collation.sh && ./refresh-collation.sh && rm ./refresh-collation.sh'