#!/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_mattermost_app_hosts_key_set() {
    grep -qP '^\s*MM_APP_HOSTS\s*=' "${CUSTOM_ENV_FILE}"
}

get_pgxivocc_networks() {
    docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}/{{.IPPrefixLen}},{{end}}' "${PGXIVOCC_CONTAINER}"
}

get_remote_mmuser_addresses() {
    local pgxivocc_networks="${1}"; shift

    docker exec "${PGXIVOCC_CONTAINER}" psql -U postgres -qtAc \
        "SELECT string_agg(DISTINCT host(client_addr), ',')
         FROM pg_stat_activity
         WHERE usename = 'mmuser'
           AND client_addr IS NOT NULL
           AND NOT EXISTS (
               SELECT 1 FROM unnest(string_to_array(rtrim('${pgxivocc_networks}', ','), ',')::inet[]) AS network
               WHERE client_addr <<= network(network))"
}

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

fill_mattermost_app_hosts() {
    local pgxivocc_networks mattermost_app_hosts

    if ! pgxivocc_networks=$(get_pgxivocc_networks) || \
       ! mattermost_app_hosts=$(get_remote_mmuser_addresses "${pgxivocc_networks}"); then
        echo "Could not read the mattermost connections, MM_APP_HOSTS left unset in ${CUSTOM_ENV_FILE}"
        return 0
    fi
    if [ -z "${mattermost_app_hosts}" ]; then
        echo "No remote mattermost connection found, MM_APP_HOSTS left unset in ${CUSTOM_ENV_FILE}"
        return 0
    fi
    append_to_custom_env "MM_APP_HOSTS=${mattermost_app_hosts}"
    echo "MM_APP_HOSTS set to '${mattermost_app_hosts}' in ${CUSTOM_ENV_FILE}"
}

check_used_postgres "xivocc"
if [[ "$USE_DB" == true ]] && ! is_mattermost_app_hosts_key_set; then
    fill_mattermost_app_hosts
fi
