cdist/cdist/conf/type/__uci_section/explorer/match

82 lines
2.5 KiB
Bash

#!/bin/sh -e
#
# 2020 Dennis Camera (dennis.camera at ssrq-sds-fds.ch)
#
# This file is part of cdist.
#
# cdist 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.
#
# cdist 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 cdist. If not, see <http://www.gnu.org/licenses/>.
#
# This explorer determines the "prefix" of the --type section matching --match
# if set, or __object_id otherwise.
squote_values() {
sed -e '/=".*"$/{s/="/='\''/;s/"$/'\''/}' \
-e "/='.*'$/"'!{s/=/='\''/;s/$/'\''/}'
}
RS=$(printf '\036')
if ! test -e "${__object:?}/parameter/match"
then
if ! echo "${__object_id:?}" | grep -q -e '^[^.]\{1,\}\.[^.]\{1,\}$'
then
echo 'Section identifiers are a package and section name separated by a "." (period).' >&2
exit 1
fi
# If no --match is given, we take the __object_id as the section identifier.
echo "${__object_id:?}"
exit 0
fi
# shellcheck disable=SC2015
test -s "${__object:?}/parameter/match" && test -s "${__object:?}/parameter/type" \
|| {
echo 'Parameters --match and --type must be used together.' >&2
exit 1
}
# Find by match
# NOTE: Apart from section types all values are printed in single quotes by UCI.
match=$(head -n 1 "${__object:?}/parameter/match" | squote_values)
if ! grep -q -e '^[^.]\{1,\}\.[^.]\{1,\}$' "${__object:?}/parameter/type"
then
echo 'Section types are a package name and section type separated by a "." (period).' >&2
exit 1
fi
sect_type_filter=$(cat "${__object:?}/parameter/type")
package_filter=${sect_type_filter%%.*}
section_filter=${sect_type_filter#*.}
# FIXME: Does not work with named sections
regex="^${package_filter}\.@${section_filter}\[[0-9]\{1,\}\]\.${match%%=*}="
matched_sections=$(
uci -s -N -d "${RS}" show "${package_filter}" 2>/dev/null \
| grep -e "${regex}" \
| while read -r _line
do
if test "${_line#*=}" = "${match#*=}"; then echo "${_line}"; fi
done \
| sed -e 's/\.[^.]*=.*$//')
if test "$(echo "${matched_sections}" | wc -l)" -gt 1
then
printf 'Found multiple matching sections:\n%s\n' "${matched_sections}" >&2
exit 1
fi
echo "${matched_sections}"