#!/bin/bash

CUSTOM_ENV_FILE="/etc/docker/xivo/custom.env"
UC_CUSTOM_ENV_FILE="/etc/docker/compose/custom.env"
XC_ENABLED_FILE="/var/lib/xivo/xc_enabled"
HA_CONF_FILE="/etc/xivo/ha.conf"
HA_SSH_KEY="/root/.ssh/xivo_id_rsa"

ACCOUNTS=(xds xivocc guest)
MDS_ACCOUNTS=(xds)

declare -A ACCOUNT_KEY=(
    [xds]=RABBITMQ_XDS_PASSWORD
    [xivocc]=RABBITMQ_XIVOCC_PASSWORD
    [guest]=RABBITMQ_GUEST_PASSWORD
)

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

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 ACCOUNT_SERVICES=(
    [xds]="xivo-amid xivo-auth xivo-sysconfd"
    [xivocc]=""
    [guest]="xivo-agentd xivo-call-logs xivo-confd xivo-dird"
)

declare -A ACCOUNT_CONTAINERS=(
    [xds]="rabbitmq webi ctid"
    [xivocc]="rabbitmq config_mgt"
    [guest]="rabbitmq"
)

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|propagate|reset [ACCOUNT]"
    echo "  ACCOUNT: one of ${ACCOUNTS[*]}, every account when omitted"
    echo "  render: rewrite the files derived from ${CUSTOM_ENV_FILE} on this XiVO, no restart"
    echo "  propagate: render, restart what uses the changed passwords, then copy them to the HA standby and the media servers"
    echo "  reset: generate a new password, then propagate it"
}

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_account() {
    local account="${1}"; shift
    if ! contains "${account}" "${ACCOUNTS[@]}"; then
        log_error "unknown bus account ${account}, managed accounts: ${ACCOUNTS[*]}"
        exit 2
    fi
}

require_known_account_if_given() {
    local account="${1:-}"
    [[ -z "${account}" ]] || require_known_account "${account}"
}

accounts_from_argument() {
    local account="${1:-}"
    if [[ -z "${account}" ]]; then
        echo "${ACCOUNTS[@]}"
    else
        echo "${account}"
    fi
}

label() {
    local account="${1}"; shift
    echo "${account} (${ACCOUNT_KEY[${account}]})"
}

env_file_value() {
    local file="${1}"; shift
    local key="${1}"; shift
    grep "^${key}=" "${file}" 2>/dev/null | tail -n 1 | cut -d= -f2-
}

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

password_of() {
    local account="${1}"; shift
    env_file_value "${CUSTOM_ENV_FILE}" "${ACCOUNT_KEY[${account}]}"
}

gen_secret() {
    openssl rand -hex 32
}

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

is_standby_node() {
    [[ "$(ha_conf_field node_type)" == "slave" ]]
}

is_main_node_with_standby() {
    [[ "$(ha_conf_field node_type)" == "master" ]]
}

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

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

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

apply_on_uc_addon() {
    local account="${1}"; shift
    local key="${ACCOUNT_KEY[${account}]}"
    local password
    [[ "${account}" == xivocc && -f "${UC_CUSTOM_ENV_FILE}" ]] || return 0
    password=$(password_of "${account}")
    [[ "$(env_file_value "${UC_CUSTOM_ENV_FILE}" "${key}")" == "${password}" ]] && return 0
    set_env_file_value "${UC_CUSTOM_ENV_FILE}" "${key}" "${password}"
    if ! xivocc-dcomp up -d xuc >/dev/null 2>&1; then
        log_warning "container xuc of the UC Add-on not recreated, run 'xivocc-dcomp up -d xuc'"
    fi
    echo "$(label "${account}") applied on the UC Add-on"
}

recreate_containers() {
    local account="${1}"; shift
    local container
    for container in ${ACCOUNT_CONTAINERS[${account}]}; do
        if ! xivo-dcomp up -d "${container}" >/dev/null 2>&1; then
            log_warning "container ${container} not recreated, run 'xivo-dcomp up -d ${container}'"
        fi
    done
}

apply_locally() {
    local account="${1}"; shift
    local before service
    before=$(files_checksum "${account}")
    render_account "${account}" || return 1
    recreate_containers "${account}"
    if [[ "$(files_checksum "${account}")" != "${before}" ]]; then
        for service in ${ACCOUNT_SERVICES[${account}]}; do
            systemctl try-restart "${service}"
        done
    fi
    apply_on_uc_addon "${account}"
    echo "$(label "${account}") applied on this XiVO"
}

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

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

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

warn_if_cc_attached() {
    local account="${1}"; shift
    [[ "${account}" == xivocc && -f "${XC_ENABLED_FILE}" ]] || return 0
    log_warning "A XiVO CC is attached to this XiVO: its xuc keeps the former $(label "${account}") password."
    log_warning "  Run on each XiVO CC (main and standby): dpkg-reconfigure xivocc-installer && xivocc-dcomp up -d xuc"
}

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 passwords here"
        exit 1
    fi
}

render() {
    local account failed=0
    require_known_account_if_given "${1:-}"
    for account in $(accounts_from_argument "${1:-}"); do
        render_account "${account}" || failed=1
    done
    return "${failed}"
}

propagate() {
    local account failed=0
    require_known_account_if_given "${1:-}"
    refuse_on_standby
    for account in $(accounts_from_argument "${1:-}"); do
        propagate_account "${account}" || failed=1
    done
    return "${failed}"
}

reset() {
    local account failed=0
    require_known_account_if_given "${1:-}"
    refuse_on_standby
    for account in $(accounts_from_argument "${1:-}"); do
        set_env_file_value "${CUSTOM_ENV_FILE}" "${ACCOUNT_KEY[${account}]}" "$(gen_secret)"
        echo "$(label "${account}") reset in ${CUSTOM_ENV_FILE}"
        propagate_account "${account}" || failed=1
    done
    for account in $(accounts_from_argument "${1:-}"); do
        warn_if_cc_attached "${account}"
    done
    return "${failed}"
}

receive() {
    local account="${1:-}"
    local password
    require_known_account "${account}"
    read -r password
    if [[ -z "${password}" ]]; then
        log_error "no password received for $(label "${account}")"
        exit 1
    fi
    set_env_file_value "${CUSTOM_ENV_FILE}" "${ACCOUNT_KEY[${account}]}" "${password}"
    apply_locally "${account}"
}

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 "$@"
