#!/bin/bash

# shellcheck source=install/usr/bin/xivocc-installer-lib/xivo-configuration-helper.sh
source "/usr/bin/xivocc-installer-lib/xivo-configuration-helper.sh"

SYNCED_VARIABLES="PLAY_AUTH_TOKEN"
SSH_KEY_DOCUMENTATION="https://documentation.xivo.solutions/en/2024.05/installation/xivocc/installation/installation.html#ssh-key-configuration"

xivo_host() {
    grep -oP '^\s*XIVO_HOST=\K.*' "${COMPOSE_PATH}/${CUSTOM_ENV_FILE}" | tail -n 1
}

check_xivo_is_ssh_reachable() {
    local xivo_host="${1}"; shift

    if ssh -n -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=3 "root@${xivo_host}" true; then
        return 0
    fi
	cat <<-EOF
	ERROR: XiVO CC cannot connect to the XiVO PBX (${xivo_host}) via SSH with an SSH key.
	Configure the SSH key, see
	  ${SSH_KEY_DOCUMENTATION}
	EOF
    exit 1
}

recreate_running_services() {
    local running_services

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

main() {
    local xivo_host
    xivo_host=$(xivo_host)
    check_xivo_is_ssh_reachable "${xivo_host}"

    local variable_name
    for variable_name in ${SYNCED_VARIABLES}; do
        copy_custom_env_variable_from_xivo_to_xivocc "${xivo_host}" "${variable_name}" || exit 1
    done

    recreate_running_services
}

main "${@}"
