#!/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.
################################################################################
################################################################################

. "${EF_ROOT}/plugins/ef/lib/utils"
ef_source_conf fm "fm.efconf"

trim() {
    echo "$@"
}

check_jq() {
    if [[ ! -x "$(which jq 2>/dev/null)" ]]; then
        error "Could not find the jq executable. Please ask your administrator to install jq to enable copy/paste file operations" "EnginFrame FM Plugin Error"
    fi
}

# Report a fatal system error
fatal() {
    fm_ef_error -fatal -message "$1" -secondary "$2" -exit 1
}


# Report a user error
error() {
    fm_ef_error -error -message "$1" -secondary "$2" -exit 1
}


fm_ef_error() {
    _fm_ef_error_level='Error'
    _fm_ef_error_code='1'
    _fm_ef_error_message=''
    _fm_ef_error_secondary_message=''

    while [ -n "$1" ]; do
        case "$1" in
            -fatal)
                _fm_ef_error_level='Fatal Error'
                ;;
            -error)
                _fm_ef_error_level='Error'
                ;;
            -msg|-message)
                _fm_ef_error_message="$2"
                shift
                ;;
            -secondary)
                _fm_ef_error_secondary_message="$2"
                shift
                ;;
            -exit)
                _fm_ef_error_code="$2"
                shift
                ;;
            *)
                ;;
        esac
        shift
    done

    . "${EF_ROOT}/plugins/ef/lib/xmlfuncs"
    _fm_ef_error_message=$(ef_xml_escape -i "${_fm_ef_error_message}")
    _fm_ef_plugin_name=$(ef_xml_escape -i "${EF_PLUGIN_NAME}")
    _fm_ef_command=$(ef_xml_escape -i "${0//${EF_ROOT}/EF_ROOT}")

    echo "<ef:error xmlns:ef=\"${EF_XMLNS}\">"
    echo "  <ef:title>${_fm_ef_plugin_name} ${_fm_ef_error_level}</ef:title>"
    echo "  <ef:message>${_fm_ef_error_message}</ef:message>"
    if [ -n "${_fm_ef_error_secondary_message}" ]; then
        _fm_ef_error_secondary_message=`ef_xml_escape -i "${_fm_ef_error_secondary_message}"`
        echo "  <ef:secondary-message>${_fm_ef_error_secondary_message}</ef:secondary-message>"
    fi
    echo '  <ef:apply-acl select="admin-only">'
    echo "    <ef:command>${_fm_ef_command}</ef:command>"
    echo '  </ef:apply-acl>'
    echo '</ef:error>'

    exit "${_fm_ef_error_code}"
}
