#!/bin/bash

XIVO_CUSTOM_ENV="/etc/docker/xivo/custom.env"
UC_CUSTOM_ENV="/etc/docker/compose/custom.env"
UC_ENABLED_FILE="/var/lib/xivo/uc_enabled"
HA_CONF="/etc/xivo/ha.conf"
MDS_SSH_KEY="/root/.ssh/rsync_xds"
STANDBY_SSH_KEY="/root/.ssh/xivo_id_rsa"
MDS_CUSTOM_ENV="/etc/docker/mds/custom.env"
STANDBY_CUSTOM_ENV="/etc/docker/xivo/custom.env"
ROTATION_ERRORS_FILE="/var/lib/xivo/play_auth_token_rotation_errors"
PUBLISHED_PLAY_AUTH_TOKEN_SHA256="591f7d299d3d8894ec426d135eb9c1a1db30d995a80fd280044ee821fd8f3cf4"

ha_node_type() {
    grep -oP '"node_type"\s*:\s*"\K[^"]*' "${HA_CONF}" 2>/dev/null
}

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

is_play_auth_token_published() {
    local token
    token=$(grep -oP '^\s*PLAY_AUTH_TOKEN=\K.*' "${XIVO_CUSTOM_ENV}" | tail -n 1 | sed -e 's/[[:space:]]*$//')
    [ "$(printf '%s' "${token}" | sha256sum | cut -d ' ' -f 1)" = "${PUBLISHED_PLAY_AUTH_TOKEN_SHA256}" ]
}

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

standby_host() {
    if [ "$(ha_node_type)" = "master" ]; then
        grep -oP '"remote_address"\s*:\s*"\K[^"]*' "${HA_CONF}"
    fi
}

is_uc_addon() {
    [ -f "${UC_ENABLED_FILE}" ]
}

create_secret() {
    local secret_length="${1}"; shift
    < /dev/urandom tr -dc A-Za-z0-9 | head -c "${secret_length}"
}

write_play_auth_token() {
    local env_file="${1}"; shift
    local new_env_file

    new_env_file=$(mktemp "${env_file}.XXXXXX") || return 1
    PLAY_AUTH_TOKEN_VALUE="${play_auth_token}" awk '
        /^[[:space:]]*PLAY_AUTH_TOKEN[[:space:]]*=/ { print "PLAY_AUTH_TOKEN=" ENVIRON["PLAY_AUTH_TOKEN_VALUE"]; found = 1; next }
        { print }
        END { if (!found) print "PLAY_AUTH_TOKEN=" ENVIRON["PLAY_AUTH_TOKEN_VALUE"] }
    ' "${env_file}" > "${new_env_file}" && cat "${new_env_file}" > "${env_file}"
    local status=$?
    rm -f "${new_env_file}"
    return "${status}"
}

recreate_running_services() {
    local dcomp="${1}"; shift
    local running_services

    running_services=$("${dcomp}" ps --services --filter status=running) || return 1
    if [ -n "${running_services}" ]; then
        # shellcheck disable=SC2086
        "${dcomp}" up -d --no-deps ${running_services}
    fi
}

push_play_auth_token() {
    local host="${1}"; shift
    local ssh_key="${1}"; shift
    local env_file="${1}"; shift

    echo "Updating PLAY_AUTH_TOKEN on ${host}..."
    {
        declare -f write_play_auth_token recreate_running_services
        printf 'play_auth_token=%s\n' "${play_auth_token}"
        printf 'write_play_auth_token %s && recreate_running_services xivo-dcomp\n' "${env_file}"
    } | ssh -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=3 -i "${ssh_key}" "root@${host}" bash -s
}

report_push_failure() {
    local host="${1}"; shift
    local env_file="${1}"; shift

	cat <<-EOF | tee -a "${ROTATION_ERRORS_FILE}"
	***************************************************************************************
	* ERROR: PLAY_AUTH_TOKEN could not be updated on ${host}.
	*
	* Copy the PLAY_AUTH_TOKEN line of ${XIVO_CUSTOM_ENV} on the XiVO PBX
	* to ${env_file} on ${host}, then run on ${host}:
	*   # xivo-dcomp up -d
	***************************************************************************************
	EOF
}

main() {
    if is_standby; then
        echo "Standby XiVO PBX: PLAY_AUTH_TOKEN is rotated by the Main XiVO PBX, nothing to do."
        exit 0
    fi
    if ! is_play_auth_token_published; then
        echo "PLAY_AUTH_TOKEN is not the published one, nothing to rotate."
        exit 0
    fi

    local mds_list
    if ! mds_list=$(mds_hosts); then
        echo "ERROR: could not list the MDS from the database, PLAY_AUTH_TOKEN was not rotated."
        exit 1
    fi
    local standby
    standby=$(standby_host)

    echo "Rotating PLAY_AUTH_TOKEN..."
    rm -f "${ROTATION_ERRORS_FILE}"
    play_auth_token=$(create_secret 64)

    local push_failed=0
    local mds
    for mds in ${mds_list}; do
        if ! push_play_auth_token "${mds}" "${MDS_SSH_KEY}" "${MDS_CUSTOM_ENV}"; then
            report_push_failure "${mds}" "${MDS_CUSTOM_ENV}"
            push_failed=1
        fi
    done
    if [ -n "${standby}" ] && ! push_play_auth_token "${standby}" "${STANDBY_SSH_KEY}" "${STANDBY_CUSTOM_ENV}"; then
        report_push_failure "${standby}" "${STANDBY_CUSTOM_ENV}"
        push_failed=1
    fi

    write_play_auth_token "${XIVO_CUSTOM_ENV}" || exit 1
    if is_uc_addon; then
        write_play_auth_token "${UC_CUSTOM_ENV}" || exit 1
    fi

    recreate_running_services xivo-dcomp
    if is_uc_addon; then
        recreate_running_services xivocc-dcomp
    fi

    if [ "${push_failed}" -ne 0 ]; then
        echo "ERROR: PLAY_AUTH_TOKEN was rotated, but some hosts were not updated, see above."
        exit 1
    fi
    echo "PLAY_AUTH_TOKEN rotated."
}

main "${@}"
