#!/bin/bash

DB_WAIT_TIMEOUT=600

run_psql() {
    psql -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
}

has_subscription() {
    local subscriptions

    subscriptions=$(run_psql -c "SELECT COUNT(*) FROM pg_subscription;" 2> /dev/null)
    [ -n "${subscriptions}" ] && [ "${subscriptions}" -gt 0 ]
}

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

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

    if ! has_subscription; 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

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

main "$@"
