miria-cli/functions.sh

109 lines
3.0 KiB
Bash

################################################################################
# Copyright 2022 Antonin Portelli
#
# This file is part of miria-cli.
#
# miria-cli is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# miria-cli is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# miria-cli. If not, see <https://www.gnu.org/licenses/>.
################################################################################
# Functions used in miria-cli commands #########################################
#######################################
# Print error message
#
# Arguments:
# Error message
#######################################
miria_error() {
echo "[miria-cli] error: $1" 1>&2
}
#######################################
# Get Mira API URL
#
# Arguments:
# None
#######################################
miria_get_url() {
if [ -e ~/.miria-url ]; then
miria_url="$(cat ~/.miria-url)"
else
miria_error 'file ~/.miria-url not found'
exit 1
fi
}
#######################################
# Execute Mira API command
#
# Arguments:
# API command,
# command argument 1 (key=value),
# ...
# command argument n (key=value)
# Outputs:
# miria_last_xml : last XML answer
# miria_last_status : last return code
# miria_last_error : last error message
#######################################
miria_api_cmd() {
local url_args=()
local cmd="$1"
miria_get_url
shift
for a in "$@"; do
url_args+=('--data-urlencode')
url_args+=("${a}")
done
miria_last_xml="$(curl -sG "${url_args[@]}" "${miria_url}/${cmd}")"
miria_last_status="$(miria_xml_get_attribute "${miria_last_xml}" '//ReturnCode' 'ADARetCode')"
miria_last_error="$(miria_xml_get_string "${miria_last_xml}" '//ErrorMsg')"
if [[ "${miria_last_status}" != "1" ]]; then
miria_error "Miria API call returned status ${miria_last_status}"
miria_error "${miria_last_error}"
exit 1
fi
}
#######################################
# Get XML string(s)
#
# Arguments:
# XML data (in string form),
# XPath of string
#######################################
miria_xml_get_string() {
local xml="$1"
local xpath="$2"
echo "${xml}" | xmllint --xpath "string(${xpath})" -
}
#######################################
# Get XML attribute value(s)
#
# Arguments:
# XML data (in string form),
# XPath of attribute (without @attribute)
# Attribute name
#######################################
miria_xml_get_attribute() {
local xml="$1"
local xpath="$2"
local attr="$3"
echo "${xml}" | xmllint --xpath "${xpath}/@${attr}" - \
| sed -E "s/ *${attr}=\"(.+)\"/\1/g"
}