From 668ad2cf0b3f0ad44ebcd2ce6ce8548770901c66 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Sun, 12 Aug 2018 11:54:35 -0400
Subject: [PATCH] [CI-SKIP] Avoid rebuilding Paper-Server if Paper-API did not
 apply

This scenario occurs when Paper-API fails, we then rebuild the patches,
however Paper-Server was left un an outdated state since the most
recent patches did not get applied to it.

This results in us reverting Paper-Server to an older state.

If Paper-API fails to apply, then Paper-Server has to be considered dirty.

This should avoid us having accidental patch reversions
---
 scripts/applyPatches.sh   | 4 ++++
 scripts/rebuildPatches.sh | 9 ++++++++-
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/scripts/applyPatches.sh b/scripts/applyPatches.sh
index 2c02b8234a..ef34ca0105 100755
--- a/scripts/applyPatches.sh
+++ b/scripts/applyPatches.sh
@@ -37,6 +37,8 @@ function applyPatch {
 
     echo "  Applying patches to $target..."
 
+    statusfile=".git/patch-apply-failed"
+    rm -f "$statusfile"
     $gitcmd am --abort >/dev/null 2>&1
 
     # Special case Windows handling because of ARG_MAX constraint
@@ -48,6 +50,7 @@ function applyPatch {
     fi
 
     if [ "$?" != "0" ]; then
+        echo 1 > "$statusfile"
         echo "  Something did not apply cleanly to $target."
         echo "  Please review above details and finish the apply then"
         echo "  save the changes with rebuildPatches.sh"
@@ -64,6 +67,7 @@ function applyPatch {
 
         exit 1
     else
+        rm -f "$statusfile"
         echo "  Patches applied cleanly to $target"
     fi
 }
diff --git a/scripts/rebuildPatches.sh b/scripts/rebuildPatches.sh
index 308ac4d0cc..6553d1aa58 100755
--- a/scripts/rebuildPatches.sh
+++ b/scripts/rebuildPatches.sh
@@ -4,6 +4,7 @@
 PS1="$"
 basedir="$(cd "$1" && pwd -P)"
 workdir="$basedir/work"
+source "$basedir/scripts/functions.sh"
 gitcmd="git -c commit.gpgsign=false -c core.safecrlf=false"
 
 echo "Rebuilding patch files from current fork state..."
@@ -60,5 +61,11 @@ function savePatches {
 }
 
 savePatches "$workdir/Spigot/Spigot-API" "Paper-API"
-savePatches "$workdir/Spigot/Spigot-Server" "Paper-Server"
+if [ -f "$basedir/Paper-API/.git/patch-apply-failed" ]; then
+    echo "$(color 1 31)[[[ WARNING ]]] $(color 1 33)- Not saving Paper-Server as it appears Paper-API did not apply clean.$(colorend)"
+    echo "$(color 1 33)If this is a mistake, delete $(color 1 34)Paper-API/.git/patch-apply-failed$(color 1 33) and run rebuild again.$(colorend)"
+    echo "$(color 1 33)Otherwise, rerun ./paper patch to have a clean Paper-API apply so the latest Paper-Server can build.$(colorend)"
+else
+    savePatches "$workdir/Spigot/Spigot-Server" "Paper-Server"
+fi
 ) || exit 1