#!/bin/bash

################################################################################
################################################################################
# Copyright 2023-2025 by NI SP Software GmbH, All rights reserved.
# Copyright 1999-2023 by Nice, srl., All rights reserved.
#
# This software includes confidential and proprietary information
# of NI SP Software GmbH ("Confidential Information").
# You shall not disclose such Confidential Information
# and shall use it only in accordance with the terms of
# the license agreement you entered into with NI SP Software.
################################################################################
################################################################################

#------------------------------------------------------------------
# SSH backend
# Utility function to execute a function or a command via ssh.
#
# Usage: ssh_function <function_name> <variables>
#
# - function_name: the name of the function to be executed via ssh
# - variables:     the variables to be exported in the function environment
#
# Usage: ssh_command <cmd>
#
# - cmd:  the command to be executed via ssh
#------------------------------------------------------------------

# Print the given arguments in a format that can be reused as shell input.
_sh_escape_args() {
    printf '%q ' "$@"
}

# Execute ssh command with the given parameters
#
# Required environment variables:
#   _portopt
#   SSH_CMD_OPTIONS
#   _login
#   FM_VROOT_HOST
_ssh_wrapper() {
    echo "${*/%/;}" | ssh -o NumberOfPasswordPrompts=0 ${_portopt} ${SSH_CMD_OPTIONS} "${_login}""${FM_VROOT_HOST}" /bin/bash
}

sh_escape() {
    printf '%q' "$1"
}

ssh_function() {
    local _ssh_func_name="$1"; shift
    local _ssh_func_vars=$([[ $# -ne 0 ]] && declare -p "$@" || echo ':')
    local _ssh_func=$(declare -f "${_ssh_func_name}")
    _ssh_wrapper "${_ssh_func_vars}" "${_ssh_func}" "${_ssh_func_name}"
}

ssh_command() {
    local _ssh_cmd=$(_sh_escape_args "$@")
    _ssh_wrapper "${_ssh_cmd}"
}
