From e336fca0debe7b4ca854e9e2d5a427ea47f0b406 Mon Sep 17 00:00:00 2001
From: Simone Margaritelli <evilsocket@gmail.com>
Date: Mon, 4 Nov 2019 17:33:35 +0100
Subject: [PATCH] fix: fixed race condition (again) on override files

---
 builder/data/usr/bin/bettercap-launcher |  2 +-
 builder/data/usr/bin/pwnlib             | 33 +++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)

diff --git a/builder/data/usr/bin/bettercap-launcher b/builder/data/usr/bin/bettercap-launcher
index 8b02ada..6b8502a 100755
--- a/builder/data/usr/bin/bettercap-launcher
+++ b/builder/data/usr/bin/bettercap-launcher
@@ -4,7 +4,7 @@ source /usr/bin/pwnlib
 # start mon0
 start_monitor_interface
 
-if is_auto_mode; then
+if is_auto_mode_no_delete; then
   /usr/bin/bettercap -no-colors -caplet pwnagotchi-auto -iface mon0
 else
   /usr/bin/bettercap -no-colors -caplet pwnagotchi-manual -iface mon0
diff --git a/builder/data/usr/bin/pwnlib b/builder/data/usr/bin/pwnlib
index 811d90f..4ba2556 100755
--- a/builder/data/usr/bin/pwnlib
+++ b/builder/data/usr/bin/pwnlib
@@ -32,6 +32,13 @@ is_interface_up() {
 
 # returns 0 if conditions for AUTO mode are met
 is_auto_mode() {
+  # check override file first
+  if [ -f /root/.pwnagotchi-manual ]; then
+    # remove the override file if found
+    rm -rf /root/.pwnagotchi-manual
+    return 1
+  fi
+
   # check override file first
   if [ -f /root/.pwnagotchi-auto ]; then
     # remove the override file if found
@@ -52,3 +59,29 @@ is_auto_mode() {
   # no override, but none of the interfaces is up -> AUTO
   return 0
 }
+
+# returns 0 if conditions for AUTO mode are met
+is_auto_mode_no_delete() {
+  # check override file first
+  if [ -f /root/.pwnagotchi-manual ]; then
+    return 1
+  fi
+
+  # check override file first
+  if [ -f /root/.pwnagotchi-auto ]; then
+    return 0
+  fi
+
+  # if usb0 is up, we're in MANU
+  if is_interface_up usb0; then
+    return 1
+  fi
+
+  # if eth0 is up (for other boards), we're in MANU
+  if is_interface_up eth0; then
+    return 1
+  fi
+
+  # no override, but none of the interfaces is up -> AUTO
+  return 0
+}
\ No newline at end of file