Implement autodetection for SAR, based on the installed system

This will detect whether SAR is present in the currently installed
OS and set the property ro.twrp.sar accordingly.
After setting the property it will call the bootscript
/sbin/sarsetup.sh (if present) to give device maintainers the
option to do setup operations depending on SAR-status, such
as modifiyng the fstab.

If no system is detected and AB_OTA_UPDATER is defined or built with
Android 10 and upwards, it will fallback to using SAR, otherwise it
will use ro.build.system_root_image as basis for deciding whether SAR
is required or not.

The property ro.twrp.sar will also be used by
TWPartitionManager::Get_Android_Root_Path()

This allows maintaining a single TWRP-build for devices switching
to SAR for Android 10.

The default behavior (when no system is installed)
is determined by the build-flags AB_OTA_UPDATER and
BOARD_BUILD_SYSTEM_ROOT_IMAGE

Change-Id: I2a48c6c81a6ea6fad6e452c06bfbe4d9da0f1e5c
diff --git a/twrp.cpp b/twrp.cpp
index dac0093..bb062f7 100755
--- a/twrp.cpp
+++ b/twrp.cpp
@@ -117,8 +117,50 @@
 	if (!TWFunc::Path_Exists(fstab_filename)) {
 		fstab_filename = "/etc/recovery.fstab";
 	}
+
+	// Begin SAR detection
+	{
+		TWPartitionManager SarPartitionManager;
+		printf("=> Processing %s for SAR-detection\n", fstab_filename.c_str());
+		if (!SarPartitionManager.Process_Fstab(fstab_filename, 1, 1)) {
+			LOGERR("Failing out of recovery due to problem with fstab.\n");
+			return -1;
+		}
+
+		mkdir("/s", 0755);
+
+#if defined(AB_OTA_UPDATER) || defined(__ANDROID_API_Q__)
+		bool fallback_sar = true;
+#else
+		bool fallback_sar = property_get_bool("ro.build.system_root_image", false);
+#endif
+
+		if(SarPartitionManager.Mount_By_Path("/s", false)) {
+			if (TWFunc::Path_Exists("/s/build.prop")) {
+				LOGINFO("SAR-DETECT: Non-SAR System detected\n");
+				property_set("ro.twrp.sar", "0");
+				rmdir("/system_root");
+			} else if (TWFunc::Path_Exists("/s/system/build.prop")) {
+				LOGINFO("SAR-DETECT: SAR System detected\n");
+				property_set("ro.twrp.sar", "1");
+			} else {
+				LOGINFO("SAR-DETECT: No build.prop found, falling back to %s\n", fallback_sar ? "SAR" : "Non-SAR");
+				property_set("ro.twrp.sar", fallback_sar ? "1" : "0");
+			}
+			SarPartitionManager.UnMount_By_Path("/s", false);
+		} else {
+			LOGINFO("SAR-DETECT: Could not mount system partition, falling back to %s\n", fallback_sar ? "SAR":"Non-SAR");
+			property_set("ro.twrp.sar", fallback_sar ? "1" : "0");
+		}
+
+		rmdir("/s");
+
+		TWFunc::check_and_run_script("/sbin/sarsetup.sh", "boot");
+	}
+	// End SAR detection
+
 	printf("=> Processing %s\n", fstab_filename.c_str());
-	if (!PartitionManager.Process_Fstab(fstab_filename, 1)) {
+	if (!PartitionManager.Process_Fstab(fstab_filename, 1, 0)) {
 		LOGERR("Failing out of recovery due to problem with fstab.\n");
 		return -1;
 	}