From 41782cb10719d04b0650f2b51e86e3adef8fdea0 Mon Sep 17 00:00:00 2001
From: Steven Armstrong <steven@icarus.ethz.ch>
Date: Mon, 29 Sep 2014 14:47:25 +0200
Subject: [PATCH] workaround special case where the desired key was already
 present more then once in target file

Signed-off-by: Steven Armstrong <steven@icarus.ethz.ch>
---
 cdist/conf/type/__ssh_authorized_key/gencode-remote | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/cdist/conf/type/__ssh_authorized_key/gencode-remote b/cdist/conf/type/__ssh_authorized_key/gencode-remote
index 8a5276b8..62c79ed2 100755
--- a/cdist/conf/type/__ssh_authorized_key/gencode-remote
+++ b/cdist/conf/type/__ssh_authorized_key/gencode-remote
@@ -78,9 +78,18 @@ fi
 # Determine the current state
 entry="$(cat "$__object/files/should")"
 state_should="$(cat "$__object/parameter/state")"
-if grep -q -F -x "$entry" "$__object/explorer/entry"; then
+num_existing_entries=$(grep -c -F -x "$entry" "$__object/explorer/entry")
+if [ $num_existing_entries -eq 1 ]; then
    state_is="present"
 else
+   # Posix grep does not define the -m option, so we can not remove a single
+   # occurence of a string from a file in the `remove_line` function. Instead
+   # _all_ occurences are removed.
+   # By using `comm` to detect conflicting entries this could lead to the
+   # situation that the key we want to add is actually removed.
+   # To workaround this we must treat 0 or more then 1 existing entries to
+   # mean current state is 'absent'. By doing this, the key is readded
+   # again after cleaning up conflicting entries.
    state_is="absent"
 fi