cdist/cdist/conf/type/__ini_value/gencode-remote

83 lines
2.5 KiB
Bash
Executable File

#!/bin/sh -e
# __ini_value/gencode-remote
#
# Generates the code. It will generate an AWK script to add, modify or remove
# the line. The script differ in some points depend on the state. If the file
# does not exist, it will only generate the script without the awk overhead.
# strip comments and newlines for a tighter script
strip_comments() {
grep -v '^[[:space:]]*\($\|#\)'
}
state_is="$(cat "$__object/explorer/state")"
state_should="$(cat "$__object/parameter/state")"
# short-circuit if nothing to do
if [ "$state_is" = "$state_should" ]; then exit; fi
# file to change
file="$(cat "$__object/parameter/file")"
# validation check
case "$state_should" in
present|commented|absent)
# Generate the basic awk struct if a file already exists
cat <<SHELL
tmpfile="\$(mktemp '${file}.cdist.XXXXXXXX')"
if [ -f '$file' ]; then
cp -p '$file' "\$tmpfile"
fi
awk -f - '$file' > "\$tmpfile" <<'AWK'
SHELL
# generate the awk script and strip unnecessary things
{
# basic functions which everyone needs
cat "$__type/files/common.awk"
# generate the script
awk -v state="$state_should" '
function parse(line) {
if(match(line, /^[ \t]*# %code_print%$/) > 0) {
if(state == "present")
print "v_print()"
else if(state == "commented")
print "v_print_commented()"
else
print "print \"script compile error! cdist state " state " unkown!\" > /dev/stderr"
}
else print line
}
{
if(match($0, /^[ \t]*# %codeblock_([^%]+)%$/) > 0) {
split($2, result, "_"); type = substr(result[2], 1, length(result[2]) - 1)
file = (ENVIRON["__type"] "/files/parts/" state "/" type ".awk")
while((getline line < file) > 0)
parse(line)
close(file)
}
else print
}' "$__type/files/base.awk"
} | strip_comments
# end of here-doc
cat <<SHELL
AWK
mv -f "\$tmpfile" '$file'
SHELL
# Do not threat it differently if the file does not exist. It's just
# absent. Because multiple explorers can say the file does not exist,
# so the file should not be completly overwritten all times.
;;
*)
echo "not done yet!" >&2
exit 1
;;
esac