#!/bin/bash

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

CUSTOM_ENV_FILE="/etc/docker/compose/custom.env"
PGXIVOCC_CONTAINER="xivocc-pgxivocc-1"

is_media_server_hosts_key_set() {
    grep -qP '^\s*MDS_HOSTS\s*=' "${CUSTOM_ENV_FILE}"
}

get_media_server_ips() {
    docker exec "${PGXIVOCC_CONTAINER}" psql -U postgres -d xivo_stats -qtAc \
        "SELECT string_agg(voip_ip, ',' ORDER BY name) FROM mediaserver WHERE name <> 'default'"
}

append_to_custom_env() {
    if [ -n "$(tail -c 1 "${CUSTOM_ENV_FILE}")" ]; then
        echo >> "${CUSTOM_ENV_FILE}"
    fi
    echo "${1}" >> "${CUSTOM_ENV_FILE}"
}

fill_media_server_hosts() {
    local media_server_ips

    if ! media_server_ips=$(get_media_server_ips); then
        echo "Could not read the media servers from xivo_stats, MDS_HOSTS left unset in ${CUSTOM_ENV_FILE}"
        return 0
    fi
    append_to_custom_env "MDS_HOSTS=${media_server_ips}"
    echo "MDS_HOSTS set to '${media_server_ips}' in ${CUSTOM_ENV_FILE}"
}

check_used_postgres "xivocc"
if [[ "$USE_DB" == true ]] && ! is_media_server_hosts_key_set; then
    fill_media_server_hosts
fi
