#!/bin/bash

MDS_RESYNC_STATE_FILE="/run/mds-resync-db.state"
INITIAL_COPY_TIMEOUT=300
INITIAL_COPY_POLL_INTERVAL=5

count_subscriptions() {
    psql -U postgres -d asterisk -Aqt -c "SELECT COUNT(*) FROM pg_subscription;" 2> /dev/null
}

count_relations_still_copying() {
    psql -U postgres -d asterisk -Aqt -c "SELECT COUNT(*) FROM pg_subscription_rel WHERE srsubstate <> 'r';" 2> /dev/null
}

is_initial_copy_done() {
    local subscriptions still_copying

    subscriptions=$(count_subscriptions)
    if [ -z "${subscriptions}" ] || [ "${subscriptions}" -eq 0 ]; then
        return 1
    fi

    still_copying=$(count_relations_still_copying)
    [ -n "${still_copying}" ] && [ "${still_copying}" -eq 0 ]
}

log_initial_copy_duration() {
    [ -n "${MDS_DB_WIPE_EPOCH}" ] || return 0

    echo "Database rebuild: $(( $(date +%s) - MDS_DB_WIPE_EPOCH ))s between the erasure of PGDATA and the end of the initial copy."
}

display_initial_copy_timeout_warning() {
    cmn_echo_important "WARNING: the initial replication copy is still running after ${INITIAL_COPY_TIMEOUT}s."
    cmn_echo_important "         Starting the services anyway; the asterisk configuration will be"
    cmn_echo_important "         regenerated once the copy is over."
}

display_initial_copy_unfinished_warning() {
    cmn_echo_important "WARNING: the initial replication copy is STILL not finished."
    cmn_echo_important "         Once it is (no row left in pg_subscription_rel with srsubstate <> 'r'),"
    cmn_echo_important "         reload the asterisk configuration with:"
    cmn_echo_important "           /usr/share/mds-upgrade/post-start.d/80-reload-asterisk-configuration"
}

wait_for_initial_copy() {
    local waited=0

    [ "${MDS_DB_RECREATED}" = "1" ] || return 0

    echo -n "Waiting up to ${INITIAL_COPY_TIMEOUT}s for the initial replication copy to complete..."
    while [ "${waited}" -lt "${INITIAL_COPY_TIMEOUT}" ]; do
        if is_initial_copy_done; then
            echo
            log_initial_copy_duration
            return 0
        fi
        sleep "${INITIAL_COPY_POLL_INTERVAL}"
        waited=$(( waited + INITIAL_COPY_POLL_INTERVAL ))
        echo -n "."
    done
    echo
    display_initial_copy_timeout_warning
    MDS_INITIAL_COPY_TIMED_OUT=1
}

catch_up_initial_copy() {
    [ "${MDS_INITIAL_COPY_TIMED_OUT}" = "1" ] || return 0

    echo "Checking again whether the initial replication copy completed..."
    if is_initial_copy_done; then
        log_initial_copy_duration
        display_upgrade_notice "Initial copy completed, regenerating the asterisk configuration..."
        /usr/share/mds-upgrade/post-start.d/80-reload-asterisk-configuration
    else
        display_initial_copy_unfinished_warning
    fi
}

import_mds_resync_state() {
    [ -f "${MDS_RESYNC_STATE_FILE}" ] || return 0

    # shellcheck disable=SC1090
    source "${MDS_RESYNC_STATE_FILE}"
}
