From 0b644b6f7b58c92c81c802b983f24603e24dac81 Mon Sep 17 00:00:00 2001
From: Georg Pfuetzenreuter
Date: Thu, 1 Jun 2023 14:40:08 +0200
Subject: Support multi-master

Read an optional configuration file to accept keys on a secondary
master.

Signed-off-by: Georg Pfuetzenreuter <mail@georg-pfuetzenreuter.net>
---
 salt-keydiff.sh | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 54 insertions(+), 2 deletions(-)

diff --git a/salt-keydiff.sh b/salt-keydiff.sh
index a6c66e0..324d0ad 100755
--- a/salt-keydiff.sh
+++ b/salt-keydiff.sh
@@ -12,9 +12,12 @@
 
 set -Ceu
 
+config='/etc/salt-scriptconfig'
+partner='null'
 minion="${1:-null}"
 key_user="${2:-null}"
 NOCOLOR="$(tput sgr0)"
+exco=0
 
 if ! command -v jq >/dev/null || ! command -v salt-key >/dev/null
 then
@@ -22,6 +25,16 @@ then
 	exit 1
 fi
 
+if [ -f "$config" ]
+then
+	# shellcheck source=/dev/null
+	. "$config"
+	if [ ! "$partner" = 'null' ]
+	then
+		ssh_key="${ssh_key:?Configuration option 'partner' requires 'ssh_key'}"
+	fi
+fi
+
 if [ "$minion" = 'null' ]
 then
 	printf 'Please specify the minion to diff against.\n'
@@ -36,8 +49,20 @@ then
 	exit 2
 fi
 
+if [ ! "$partner" = 'null' ]
+then
+	key_salt_remote="$(ssh -qi "$ssh_key" "$partner" salt-key --out json -f "$minion" | jq --arg minion "$minion" -r '.minions_pre[$minion]')"
+	
+	if [ ! "$key_salt" = "$key_salt_remote" ]
+	then
+		printf 'Local and remote keys do not match, bailing out.\n'
+		exit 2
+	fi
+fi
+
 if [ "$key_user" = 'null' ]
 then
+	# shellcheck disable=SC2016
 	printf 'Enter fingerprint to diff against (run `salt-call --local key.finger` on the minion)\n'
 	read -r key_user
 fi
@@ -46,10 +71,37 @@ if [ "$key_salt" = "$key_user" ]
 then
 	GREEN="$(tput setaf 2)"
 	printf '%sMatches%s\n' "$GREEN" "$NOCOLOR"
-	salt-key --out=yaml -a "$minion"
+	printf 'Accept? (y/n)\n'
+	read -r answer
+	if [ "$answer" = 'y' ]
+	then
+		if salt-key --out=quiet -yqa "$minion" >/dev/null
+		then
+			printf 'Accepted on local master\n'
+		else
+			printf 'Failed to accept key on local master\n'
+			exco=1
+		fi
+
+		if [ ! "$partner" = 'null' ]
+		then
+			if ssh -qi "$ssh_key" "$partner" salt-key --out=quiet -yqa "$minion" >/dev/null
+			then
+				printf 'Accepted on remote master\n'
+			else
+				printf 'Failed to accept key on remote master\n'
+				exco=1
+			fi
+		fi
+	else
+		printf 'Bye\n'
+		exco=2
+	fi
 elif [ ! "$key_salt" = "$key_user" ]
 then
 	RED="$(tput setaf 1)"
 	printf '%sMismatch%s\n' "$RED" "$NOCOLOR"
-	exit 2
+	exco=2
 fi
+
+exit "$exco"
-- 
cgit v1.2.3