From d068dfd6218956a9bf07652327dc4e04209d3e95 Mon Sep 17 00:00:00 2001
From: Steven Armstrong <steven@icarus.ethz.ch>
Date: Tue, 10 Dec 2013 11:02:10 +0100
Subject: [PATCH] escape and thereby preserve quotes in values

Signed-off-by: Steven Armstrong <steven@icarus.ethz.ch>
---
 cdist/conf/type/__key_value/gencode-remote | 27 ++++++++++++++--------
 1 file changed, 18 insertions(+), 9 deletions(-)

diff --git a/cdist/conf/type/__key_value/gencode-remote b/cdist/conf/type/__key_value/gencode-remote
index c1a6bca8..ec91894f 100755
--- a/cdist/conf/type/__key_value/gencode-remote
+++ b/cdist/conf/type/__key_value/gencode-remote
@@ -26,8 +26,8 @@ state_should=present
 
 file="$(cat "$__object/parameter/file")"
 delimiter="$(cat "$__object/parameter/delimiter")"
-value="$(cat "$__object/parameter/value")"
-
+# escape double quotes, as that is what we use ourself below
+value_escaped="$(cat "$__object/parameter/value" | sed -e "s/\([\"]\)/\\\\\1/g")"
 state_is="$(cat "$__object/explorer/state")"
 
 [ "$state_is" = "$state_should" ] && exit 0
@@ -35,20 +35,29 @@ state_is="$(cat "$__object/explorer/state")"
 case "$state_should" in
     absent)
         # remove lines starting with key
-        echo "sed '/^$key\($delimiter\+\)/d' \"$file\" > \"$file.cdist-tmp\""
-        echo "mv \"$file.cdist-tmp\" \"$file\""
+        cat << DONE
+tmpfile=\$(mktemp ${file}.cdist.XXXXXXXXXX)
+# preserve ownership and permissions by copying existing file over tmpfile
+cp -p "$file" "\$tmpfile"
+sed '/^$key\($delimiter\+\)/d' "$file" > "\$tmpfile"
+mv -f "\$tmpfile" "$file"
+DONE
     ;;
     present)
         case "$state_is" in
             absent)
                 # add new key and value
-                echo "echo \"${key}${delimiter}${value}\" >> \"$file\""
+                printf 'echo "%s%s%s" >> "%s"' "$key" "$delimiter" "$value_escaped" "$file"
             ;;
             wrongvalue)
                 # change exisiting value
-                printf 'sed "s|^%s\(%s\+\).*|%s\\1%s|" "%s" > "%s.cdist-tmp"\n' \
-                    "$key" "$delimiter" "$key" "$value" "$file" "$file"
-                echo "mv \"$file.cdist-tmp\" \"$file\""
+                cat << DONE
+tmpfile=\$(mktemp ${file}.cdist.XXXXXXXXXX)
+# preserve ownership and permissions by copying existing file over tmpfile
+cp -p "$file" "\$tmpfile"
+sed "s|^$key\($delimiter\+\).*|$key\\1$value_escaped|" "$file" > "\$tmpfile"
+mv -f "\$tmpfile" "$file"
+DONE
             ;;
             *)
                 echo "Unknown explorer state: $state_is" >&2
@@ -58,4 +67,4 @@ case "$state_should" in
     *)
        echo "Unknown state: $state_should" >&2
        exit 1
-esac 
+esac