#!/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"

usage() {
    echo "Usage: $(basename "${0}") [--replace] [--on-change COMMAND] VARIABLE" >&2
    echo "  without option: add VARIABLE to the media servers that do not have it, never overwrite" >&2
    echo "  --replace: also overwrite a different value" >&2
    echo "  --on-change COMMAND: run COMMAND on a media server whose value was overwritten" >&2
}

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';"
}

remote_script() {
    local variable="${1}"; shift
    local value="${1}"; shift
    local replace="${1}"; shift
    local on_change="${1}"; shift
    printf 'variable=%q\nvalue=%q\nreplace=%q\non_change=%q\nfile=%q\n' "${variable}" "${value}" "${replace}" "${on_change}" "${MDS_CUSTOM_ENV}"
    cat <<'EOF'
if ! grep -q "^${variable}=" "${file}" 2>/dev/null; then
    printf '%s=%s\n' "${variable}" "${value}" >> "${file}" && echo added
    exit
fi
current=$(grep "^${variable}=" "${file}" | tail -n 1 | cut -d= -f2-)
if [ "${current}" = "${value}" ] || [ "${replace}" != yes ]; then
    echo present
    exit
fi
sed -i "/^${variable}=/d" "${file}" && printf '%s=%s\n' "${variable}" "${value}" >> "${file}" || exit 1
if [ -n "${on_change}" ]; then
    bash -c "${on_change}" >/dev/null || exit 1
fi
echo replaced
EOF
}

push_to_mds() {
    local host="${1}"; shift
    remote_script "$@" \
        | ssh -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=3 -i "${MDS_SSH_KEY}" "root@${host}" bash -s
}

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 replace=no on_change=""
    while [[ "${1:-}" == --* ]]; do
        case "${1}" in
            --replace) replace=yes; shift;;
            --on-change) on_change="${2:-}"; shift 2;;
            *) usage; return 2;;
        esac
    done
    local variable="${1:-}"
    if [[ -z "${variable}" ]]; then
        usage
        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 result failed=0
    for host in ${hosts}; do
        if result=$(push_to_mds "${host}" "${variable}" "${value}" "${replace}" "${on_change}" 2>/dev/null) && [[ -n "${result}" ]]; then
            echo "${variable} ${result} on the media server ${host}"
        else
            print_manual_step "${host}" "${variable}"
            failed=1
        fi
    done
    return "${failed}"
}

main "$@"
