#!/bin/bash

DB_WAIT_TIMEOUT=600

run_psql() {
    psql -w -h localhost -U postgres -d asterisk -Aqt -v ON_ERROR_STOP=1 "$@"
}

is_db_ready() {
    run_psql -c "SELECT 1;" > /dev/null 2>&1
}

wait_for_db() {
    local waited

    for ((waited = 0; waited < DB_WAIT_TIMEOUT; waited++)); do
        is_db_ready && return 0
        sleep 1
    done
    return 1
}

count_subscriptions() {
    run_psql -c "SELECT COUNT(*) FROM pg_subscription WHERE subdbid = (SELECT oid FROM pg_database WHERE datname = current_database());"
}

enable_disabled_subscriptions() {
    run_psql <<-'EOF'
	DO $$
	DECLARE subscription record;
	BEGIN
	    FOR subscription IN SELECT subname FROM pg_subscription
	        WHERE NOT subenabled AND subdbid = (SELECT oid FROM pg_database WHERE datname = current_database()) LOOP
	        EXECUTE format('ALTER SUBSCRIPTION %I ENABLE', subscription.subname);
	    END LOOP;
	END $$;
	EOF
}

refresh_subscriptions() {
    local subscriptions subscription

    subscriptions=$(run_psql -c "SELECT subname FROM pg_subscription WHERE subdbid = (SELECT oid FROM pg_database WHERE datname = current_database());") || return 1

    for subscription in ${subscriptions}; do
        run_psql -c "ALTER SUBSCRIPTION \"${subscription}\" REFRESH PUBLICATION;" || return 1
    done
}

main() {
    local subscriptions

    if ! wait_for_db; then
        echo "ERROR: the media server database did not answer within ${DB_WAIT_TIMEOUT}s." >&2
        exit 1
    fi

    if ! subscriptions=$(count_subscriptions); then
        echo "ERROR: the subscriptions of the media server database could not be read." >&2
        exit 1
    fi

    if [ "${subscriptions}" -eq 0 ]; then
        echo "ERROR: the media server database has no subscription to the XiVO Main." >&2
        exit 1
    fi

    if ! enable_disabled_subscriptions; then
        echo "ERROR: the subscription to the XiVO Main could not be enabled." >&2
        exit 1
    fi

    if ! refresh_subscriptions; then
        echo "WARNING: the subscription to the XiVO Main is enabled but could not be refreshed." >&2
        echo "         Tables published since its creation replicate once refreshed with:" >&2
        echo "           ALTER SUBSCRIPTION <name> REFRESH PUBLICATION;" >&2
    fi

    echo "The subscription to the XiVO Main is enabled."
}

main "$@"
