#!/bin/bash

get_key_in_env() {
    local key_name="${1}"; shift
    local compose_path=${1:-"/etc/docker/xivo"}; shift
    local custom_env_file=${1:-"custom.env"}; shift
    local key_value

    if key_value=$(grep -oP -m 1 "${key_name}=\K.*" ${compose_path}/${custom_env_file}); then
        echo "${key_value}"
    else
        echo ""
    fi
}

get_usm_backend_token() {
    local usm_backend_url="${1}"; shift
    local xivo_uuid=$(cat /etc/default/xivo | grep -oP 'XIVO_UUID=(.*)$' | tail -n 1 | cut -d '=' -f 2)
    if token=$(curl --fail --connect-timeout 10 --max-time 20 "${usm_backend_url}/usm/token?xivo_uuid=${xivo_uuid}"); then
        echo "${token}"
    else
        echo "error"
    fi
}

add_key_in_env() {
    local key_name="${1}"; shift
    local key_value="${1}"; shift
    local compose_path=${1:-"/etc/docker/xivo"}; shift
    local custom_env_file=${1:-"custom.env"}; shift

    echo "${key_name}=${key_value}" >> "${compose_path}/${custom_env_file}"
}

if dpkg --compare-versions "$XIVO_VERSION_INSTALLED" "<<" "2023.05.00"; then
    USM_BACKEND_URL=$(get_key_in_env "USM_BACKEND_URL")
    if [ -z "${USM_BACKEND_URL}" ]; then
        USM_BACKEND_URL=$(get_key_in_env "USM_BACKEND_URL" "/etc/docker/xivo" "factory.env")
    fi
    USM_BACKEND_TOKEN=$(get_usm_backend_token "${USM_BACKEND_URL}")
    if [ "${USM_BACKEND_TOKEN}" == "error" ];then
        echo -e "\e[1;33m WARNING: could not retrieve USM BACKEND TOKEN at ${USM_BACKEND_URL}/usm/token\e[0m"
        echo -e "\e[1;33m WARNING: USM will not be able to push data to the backend\e[0m"
    else
        add_key_in_env "USM_BACKEND_TOKEN" "${USM_BACKEND_TOKEN}"
    fi
    exit 0
else
    exit 0
fi