Skip to content

Instantly share code, notes, and snippets.

@arbakker
Created November 25, 2021 08:42
Show Gist options
  • Save arbakker/3edaf0e645549f94cbc05e422e9b268b to your computer and use it in GitHub Desktop.
Save arbakker/3edaf0e645549f94cbc05e422e9b268b to your computer and use it in GitHub Desktop.
Bash for resolving OpenSearch template URLS for INSPIRE Atom services
#!/usr/bin/env bash
set -euo pipefail
PROGRAM_NAME="$0"
function get-query-params() {
file="$1"
params=$(
xmlstarlet sel -T \
-N os="http://a9.com/-/spec/opensearch/1.1/" \
-t -m "//os:OpenSearchDescription/os:Query/@*" \
-n -v "concat(name(),',', .)" "$file" # concat(substring-before(name(), ":"), "_", substring-after(name(), ":"))
)
echo -n "$params" | tr ":" "_" | jq --slurp --raw-input 'split("\n") | .[1:] | map(split(",")) | map({(.[0]) : .[1]}) | add'
}
function get-xpath-att() {
file="$1"
xpath="$2"
att="$3"
xmlstarlet sel -T \
-N os="http://a9.com/-/spec/opensearch/1.1/" \
-t -m "$xpath" \
-n -v "$att" "$file"
}
function get-params-url() {
local url="$1"
local params=""
for param in $(grep -oP "\{.*?\}" <<<"$url"); do
param="$(echo -n ${param:1:-2})" # slice string from 1 till -2
params="${params}${param},"
done
echo -n "${params::-1}"
}
function usage() {
echo "DESCRIPTION: resolve template query links opensearch description documents"
echo "USAGE: ${PROGRAM_NAME} <opensearch description url/file> <url-type, values: get-ds, desc-ds, results>"
exit 1
}
if [[ $# -ne 2 ]]; then
usage
fi
FILE="$1"
MODE="$2"
if [[ $FILE == https://* ]] || [[ $FILE == http://* ]]; then
NEW_FILE="/tmp/$(uuidgen).xml"
curl -s "$FILE" -o "$NEW_FILE"
FILE="$NEW_FILE"
fi
QUERY_PARAMS=$(get-query-params "$FILE")
if [[ $MODE == "get-ds" ]]; then
URL=$(get-xpath-att "$FILE" "//os:OpenSearchDescription/os:Url[@rel='results'][last()]" "@template")
elif [[ $MODE == "desc-ds" ]]; then
URL=$(get-xpath-att "$FILE" "//os:OpenSearchDescription/os:Url[@rel='describedby' and @type='application/atom+xml']" "@template")
elif [[ $MODE == "results" ]]; then
URL=$(get-xpath-att "$FILE" "//os:OpenSearchDescription/os:Url[@rel='results' and @type='application/atom+xml']" "@template")
else
echo "ERROR: unsupported url-type ${MODE}"
echo " supported url-types are get-ds, desc-ds"
exit 1
fi
URL_PARAM_KEYS="$(get-params-url "$URL")"
for URL_PARAM_KEY in ${URL_PARAM_KEYS//,/$IFS}; do
URL_PARAM_KEY_ESCP=$(tr ":" "_" <<<"$URL_PARAM_KEY")
URL_PARAM_VAL=$(jq -r ".${URL_PARAM_KEY_ESCP}" <<<$QUERY_PARAMS | tr "_" ":")
if [[ $URL_PARAM_VAL == "null" ]]; then
echo "ERROR: unable to find value for query param: $URL_PARAM_KEY"
exit 1
fi
URL=$(sed "s|{${URL_PARAM_KEY}?}|${URL_PARAM_VAL}|g" <<<"$URL")
done
echo "$URL"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment