#!/bin/bash

XIVO_CUSTOM_ENV="/etc/docker/xivo/custom.env"
MDS_CUSTOM_ENV="/etc/docker/mds/custom.env"
MDS_SSH_KEY="/root/.ssh/rsync_xds"

log_warning() {
    echo -e "\e[1;33mWARN: $*\e[0m" >&2
}

xivo_value() {
    local variable="${1}"; shift
    grep "^${variable}=" "${XIVO_CUSTOM_ENV}" | tail -n 1 | cut -d= -f2-
}

mds_hosts() {
    psql -U asterisk -d asterisk --quiet -tAc "select voip_ip from mediaserver where name <> 'default';"
}

push_to_mds() {
    local host="${1}"; shift
    local variable="${1}"; shift
    local value="${1}"; shift
    printf '%s=%s\n' "${variable}" "${value}" \
        | ssh -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=3 -i "${MDS_SSH_KEY}" "root@${host}" \
            "grep -q '^${variable}=' ${MDS_CUSTOM_ENV} || cat >> ${MDS_CUSTOM_ENV}"
}

print_manual_step() {
    local host="${1}"; shift
    local variable="${1}"; shift
    log_warning "${variable} not pushed to the media server ${host}."
    log_warning "  Copy the line ${variable}=... of ${XIVO_CUSTOM_ENV} on this XiVO into ${MDS_CUSTOM_ENV} on the media server, before running mds-upgrade there."
}

main() {
    local variable="${1}"; shift
    if [[ -z "${variable}" ]]; then
        echo "Usage: $(basename "${0}") VARIABLE" >&2
        return 2
    fi
    local value
    value=$(xivo_value "${variable}")
    if [[ -z "${value}" ]]; then
        log_warning "${variable} is not set in ${XIVO_CUSTOM_ENV}, nothing pushed to the media servers."
        return 1
    fi
    local hosts
    if ! hosts=$(mds_hosts); then
        log_warning "cannot read the media servers from the database, ${variable} not pushed."
        log_warning "  Copy the line ${variable}=... of ${XIVO_CUSTOM_ENV} on this XiVO into ${MDS_CUSTOM_ENV} on each media server, before running mds-upgrade there."
        return 1
    fi
    local host failed=0
    for host in ${hosts}; do
        if push_to_mds "${host}" "${variable}" "${value}" 2>/dev/null; then
            echo "${variable} present on the media server ${host}"
        else
            print_manual_step "${host}" "${variable}"
            failed=1
        fi
    done
    return "${failed}"
}

main "$@"
