From 43b3126b5cd2253330edf73930d37f17eaf4328f Mon Sep 17 00:00:00 2001
From: Andrew Janke <andrew@apjanke.net>
Date: Wed, 23 Sep 2015 18:41:48 -0400
Subject: [PATCH] installer: use timestamped backups to preserve all old zshrcs

---
 tools/install.sh   | 22 ++++++++++++++++++++--
 tools/uninstall.sh | 15 ++++++++-------
 2 files changed, 28 insertions(+), 9 deletions(-)

diff --git a/tools/install.sh b/tools/install.sh
index e69ce4b83..66da05690 100755
--- a/tools/install.sh
+++ b/tools/install.sh
@@ -84,10 +84,28 @@ setup_ohmyzsh() {
 }
 
 setup_zshrc() {
+	# Keep most recent old .zshrc at .zshrc.pre-oh-my-zsh, and older ones
+	# with datestamp of installation that moved them aside, so we never actually
+	# destroy a user's original zshrc
 	echo "${BLUE}Looking for an existing zsh config...${RESET}"
+
+	# Must use this exact name so uninstall.sh can find it
+	OLD_ZSHRC=~/.zshrc.pre-oh-my-zsh
 	if [ -f ~/.zshrc ] || [ -h ~/.zshrc ]; then
-		echo "${YELLOW}Found ~/.zshrc.${GREEN} Backing up to ~/.zshrc.pre-oh-my-zsh.${RESET}"
-		mv ~/.zshrc ~/.zshrc.pre-oh-my-zsh
+		if [ -e "$OLD_ZSHRC" ]; then
+			OLD_OLD_ZSHRC="${OLD_ZSHRC}-$(date +%Y-%m-%d_%H-%M-%S)"
+			if [ -e "$OLD_OLD_ZSHRC" ]; then
+				error "$OLD_OLD_ZSHRC exists. Can't back up ${OLD_ZSHRC}"
+				error "re-run the installer again in a couple of seconds"
+				exit 1
+			fi
+			mv "$OLD_ZSHRC" "${OLD_OLD_ZSHRC}"
+
+			echo "${YELLOW}Found old ~/.zshrc.pre-oh-my-zsh." \
+				"${GREEN}Backing up to ${OLD_OLD_ZSHRC}${RESET}"
+		fi
+		echo "${YELLOW}Found ~/.zshrc.${RESET} ${GREEN}Backing up to ${OLD_ZSHRC}${RESET}"
+		mv ~/.zshrc "$OLD_ZSHRC"
 	fi
 
 	echo "${BLUE}Using the Oh My Zsh template file and adding it to ~/.zshrc.${RESET}"
diff --git a/tools/uninstall.sh b/tools/uninstall.sh
index bf2244be8..9793be2a1 100644
--- a/tools/uninstall.sh
+++ b/tools/uninstall.sh
@@ -10,16 +10,17 @@ if [ -d ~/.oh-my-zsh ]; then
 fi
 
 echo "Looking for original zsh config..."
-if [ -f ~/.zshrc.pre-oh-my-zsh ] || [ -h ~/.zshrc.pre-oh-my-zsh ]; then
-  echo "Found ~/.zshrc.pre-oh-my-zsh -- Restoring to ~/.zshrc";
+ZSHRC_ORIG=~/.zshrc.pre-oh-my-zsh
+if [ -e "$ZSHRC_ORIG" ]; then
+  echo "Found $ZSHRC_ORIG -- Restoring to ~/.zshrc"
 
-  if [ -f ~/.zshrc ] || [ -h ~/.zshrc ]; then
-    ZSHRC_SAVE=".zshrc.omz-uninstalled-$(date +%Y%m%d%H%M%S)";
-    echo "Found ~/.zshrc -- Renaming to ~/${ZSHRC_SAVE}";
-    mv ~/.zshrc ~/"${ZSHRC_SAVE}";
+  if [ -e ~/.zshrc ]; then
+    ZSHRC_SAVE=~/.zshrc.omz-uninstalled-$(date +%Y-%m-%d_%H-%M-%S)
+    echo "Found ~/.zshrc -- Renaming to ${ZSHRC_SAVE}"
+    mv ~/.zshrc "${ZSHRC_SAVE}"
   fi
 
-  mv ~/.zshrc.pre-oh-my-zsh ~/.zshrc;
+  mv "$ZSHRC_ORIG" ~/.zshrc
 
   echo "Your original zsh config was restored. Please restart your session."
 else