#!/bin/bash

CUSTOM_ENV_FILE="/etc/docker/xivo/custom.env"
HA_CONF_FILE="/etc/xivo/ha.conf"
HA_SSH_KEY="/root/.ssh/xivo_id_rsa"
SECRET_LENGTH=64

MANAGED_KEYS=(RABBITMQ_XDS_PASSWORD RABBITMQ_GUEST_PASSWORD RABBITMQ_XIVOCC_PASSWORD)
RESETTABLE_KEYS=(RABBITMQ_XDS_PASSWORD)
MDS_KEYS=(RABBITMQ_XDS_PASSWORD)

declare -A DERIVED_FILE_KEY=(
    [/etc/xivo-amid/conf.d/050-xivo-bus.yml]=RABBITMQ_XDS_PASSWORD
    [/etc/xivo-auth/conf.d/050-xivo-bus.yml]=RABBITMQ_XDS_PASSWORD
    [/etc/xivo/sysconfd/conf.d/050-xivo-bus.conf]=RABBITMQ_XDS_PASSWORD
    [/etc/xivo-agentd/conf.d/050-xivo-bus.yml]=RABBITMQ_GUEST_PASSWORD
    [/etc/xivo-call-logd/conf.d/050-xivo-bus.yml]=RABBITMQ_GUEST_PASSWORD
    [/etc/xivo-confd/conf.d/050-xivo-bus.yml]=RABBITMQ_GUEST_PASSWORD
    [/etc/xivo-dird/conf.d/050-xivo-bus.yml]=RABBITMQ_GUEST_PASSWORD
)

declare -A DERIVED_FILE_TEMPLATE=(
    [/etc/xivo-amid/conf.d/050-xivo-bus.yml]=$'bus:\n  username: xds\n  password: %s'
    [/etc/xivo-auth/conf.d/050-xivo-bus.yml]=$'amqp:\n  uri: amqp://xds:%s@localhost:5672/'
    [/etc/xivo/sysconfd/conf.d/050-xivo-bus.conf]=$'[bus]\npassword = %s'
    [/etc/xivo-agentd/conf.d/050-xivo-bus.yml]=$'bus:\n  username: guest\n  password: %s'
    [/etc/xivo-call-logd/conf.d/050-xivo-bus.yml]=$'bus:\n  username: guest\n  password: %s'
    [/etc/xivo-confd/conf.d/050-xivo-bus.yml]=$'bus:\n  username: guest\n  password: %s'
    [/etc/xivo-dird/conf.d/050-xivo-bus.yml]=$'bus:\n  username: guest\n  password: %s'
)

declare -A KEY_SERVICES=(
    [RABBITMQ_XDS_PASSWORD]="xivo-amid xivo-auth xivo-sysconfd"
    [RABBITMQ_GUEST_PASSWORD]="xivo-agentd xivo-call-logs xivo-confd xivo-dird"
    [RABBITMQ_XIVOCC_PASSWORD]=""
)

declare -A KEY_CONTAINERS=(
    [RABBITMQ_XDS_PASSWORD]="rabbitmq webi ctid"
    [RABBITMQ_GUEST_PASSWORD]="rabbitmq"
    [RABBITMQ_XIVOCC_PASSWORD]="rabbitmq config_mgt"
)

MDS_APPLY_COMMAND="value=\$(grep '^RABBITMQ_XDS_PASSWORD=' /etc/docker/mds/custom.env | tail -n 1 | cut -d= -f2-) && mkdir -p /etc/xivo/sysconfd/conf.d && (umask 077 && printf '[bus]\npassword = %s\n' \"\${value}\" > /etc/xivo/sysconfd/conf.d/050-xivo-bus.conf) && systemctl try-restart xivo-sysconfd && xivo-dcomp up -d rabbitmq"

usage() {
    echo "Usage: ${0##*/} render [KEY] | propagate [KEY] | reset KEY"
    echo "  render: rewrite the files derived from ${CUSTOM_ENV_FILE} on this XiVO, no restart"
    echo "  propagate: render, restart what uses the changed values, then copy them to the HA standby and the media servers"
    echo "  reset: generate a new value for KEY, then propagate it"
    echo "  KEY defaults to every managed key for render and propagate: ${MANAGED_KEYS[*]}"
    echo "  reset accepts: ${RESETTABLE_KEYS[*]}"
}

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

log_error() {
    echo -e "\e[1;31mERROR: $*\e[0m" >&2
}

require_root() {
    if [[ "$(id -u)" -ne 0 ]]; then
        log_error "${0##*/} must be run as root"
        exit 1
    fi
}

contains() {
    local needle="${1}"; shift
    local item
    for item in "$@"; do
        [[ "${item}" == "${needle}" ]] && return 0
    done
    return 1
}

require_known_key() {
    local key="${1}"; shift
    local allowed=("$@")
    if ! contains "${key}" "${allowed[@]}"; then
        log_error "unsupported key ${key}, expected one of: ${allowed[*]}"
        exit 2
    fi
}

custom_env_value() {
    local key="${1}"; shift
    grep "^${key}=" "${CUSTOM_ENV_FILE}" | tail -n 1 | cut -d= -f2-
}

set_custom_env_value() {
    local key="${1}"; shift
    local value="${1}"; shift
    sed -i "/^${key}=/d" "${CUSTOM_ENV_FILE}"
    printf '%s=%s\n' "${key}" "${value}" >> "${CUSTOM_ENV_FILE}"
}

create_secret() {
    < /dev/urandom tr -dc A-Za-z0-9 | head -c "${SECRET_LENGTH}"
}

ha_node_type() {
    python3 -c 'import json, sys; print(json.load(open(sys.argv[1])).get("node_type", ""))' "${HA_CONF_FILE}" 2>/dev/null
}

ha_remote_address() {
    python3 -c 'import json, sys; print(json.load(open(sys.argv[1])).get("remote_address", ""))' "${HA_CONF_FILE}" 2>/dev/null
}

is_standby_node() {
    [[ "$(ha_node_type)" == "slave" ]]
}

is_main_node_with_standby() {
    [[ "$(ha_node_type)" == "master" ]]
}

derived_files_of() {
    local key="${1}"; shift
    local file
    for file in "${!DERIVED_FILE_KEY[@]}"; do
        [[ "${DERIVED_FILE_KEY[${file}]}" == "${key}" ]] && echo "${file}"
    done
}

render_key() {
    local key="${1}"; shift
    local value file
    value=$(custom_env_value "${key}")
    if [[ -z "${value}" ]]; then
        log_warning "${key} is not set in ${CUSTOM_ENV_FILE}, its files are not written"
        return 1
    fi
    for file in $(derived_files_of "${key}"); do
        mkdir -p "$(dirname "${file}")"
        (umask 077 && printf "${DERIVED_FILE_TEMPLATE[${file}]}\n" "${value}" > "${file}")
    done
}

files_checksum() {
    local key="${1}"; shift
    local file
    for file in $(derived_files_of "${key}"); do
        cat "${file}" 2>/dev/null
    done | md5sum
}

apply_locally() {
    local key="${1}"; shift
    local before service
    before=$(files_checksum "${key}")
    render_key "${key}" || return 1
    if [[ -n "${KEY_CONTAINERS[${key}]}" ]]; then
        xivo-dcomp up -d ${KEY_CONTAINERS[${key}]} >/dev/null
    fi
    if [[ "$(files_checksum "${key}")" != "${before}" ]]; then
        for service in ${KEY_SERVICES[${key}]}; do
            systemctl try-restart "${service}"
        done
    fi
    echo "${key} applied on this XiVO"
}

push_to_standby() {
    local key="${1}"; shift
    local remote_address
    remote_address=$(ha_remote_address)
    if custom_env_value "${key}" | ssh -o BatchMode=yes -o ConnectTimeout=5 -i "${HA_SSH_KEY}" "root@${remote_address}" "xivo-env-secret receive ${key}" >/dev/null; then
        echo "${key} applied on the HA standby ${remote_address}"
        return 0
    fi
    log_warning "${key} not applied on the HA standby ${remote_address}."
    log_warning "  Run 'xivo-env-secret propagate ${key}' again once the standby is reachable with ${HA_SSH_KEY} (see xivo-sync -i)."
    return 1
}

push_to_media_servers() {
    local key="${1}"; shift
    xivo-push-custom-env-var-to-mds --replace --on-change "${MDS_APPLY_COMMAND}" "${key}"
}

propagate_key() {
    local key="${1}"; shift
    local failed=0
    apply_locally "${key}" || failed=1
    if is_main_node_with_standby; then
        push_to_standby "${key}" || failed=1
    fi
    if contains "${key}" "${MDS_KEYS[@]}"; then
        push_to_media_servers "${key}" || failed=1
    fi
    return "${failed}"
}

refuse_on_standby() {
    if is_standby_node; then
        log_error "this XiVO is an HA standby: run ${0##*/} on the main XiVO, it copies the values here"
        exit 1
    fi
}

keys_from_argument() {
    local key="${1:-}"
    if [[ -z "${key}" ]]; then
        echo "${MANAGED_KEYS[@]}"
    else
        echo "${key}"
    fi
}

require_known_key_if_given() {
    local key="${1:-}"
    [[ -z "${key}" ]] || require_known_key "${key}" "${MANAGED_KEYS[@]}"
}

render() {
    local key failed=0
    require_known_key_if_given "${1:-}"
    for key in $(keys_from_argument "${1:-}"); do
        render_key "${key}" || failed=1
    done
    return "${failed}"
}

propagate() {
    local key failed=0
    require_known_key_if_given "${1:-}"
    refuse_on_standby
    for key in $(keys_from_argument "${1:-}"); do
        propagate_key "${key}" || failed=1
    done
    return "${failed}"
}

reset() {
    local key="${1:-}"
    if [[ -z "${key}" ]]; then
        usage >&2
        exit 2
    fi
    require_known_key "${key}" "${RESETTABLE_KEYS[@]}"
    refuse_on_standby
    set_custom_env_value "${key}" "$(create_secret)"
    echo "${key} reset in ${CUSTOM_ENV_FILE}"
    propagate_key "${key}"
}

receive() {
    local key="${1:-}"
    local value
    require_known_key "${key}" "${MANAGED_KEYS[@]}"
    read -r value
    if [[ -z "${value}" ]]; then
        log_error "no value received for ${key}"
        exit 1
    fi
    set_custom_env_value "${key}" "${value}"
    apply_locally "${key}"
}

main() {
    local action="${1:-}"
    shift
    case "${action}" in
        render) require_root; render "$@";;
        propagate) require_root; propagate "$@";;
        reset) require_root; reset "$@";;
        receive) require_root; receive "$@";;
        -h|--help) usage;;
        *) usage >&2; exit 2;;
    esac
}

main "$@"
