prebuilt: backuptool: Implement dynamic system mount for A-only

* Dynamically mount system to the path chosen by the recovery through backuptool
* This can be helpful because of the fragmentation that will happen with system mount in recovery after Q

Change-Id: I2d1e775efcf87e33319bc7790d1e54bca72116d3
diff --git a/prebuilt/common/bin/backuptool.sh b/prebuilt/common/bin/backuptool.sh
index 71d9973..74e13b5 100755
--- a/prebuilt/common/bin/backuptool.sh
+++ b/prebuilt/common/bin/backuptool.sh
@@ -4,7 +4,8 @@
 #
 
 export C=/tmp/backupdir
-export S=$2
+export SYSDEV="$(readlink -nf "$2")"
+export SYSFS="$3"
 export V=17.1
 
 export ADDOND_VERSION=1
@@ -94,11 +95,39 @@
 fi
 }
 
+determine_system_mount() {
+  if grep -q -e"^$SYSDEV" /proc/mounts; then
+    umount $(grep -e"^$SYSDEV" /proc/mounts | cut -d" " -f2)
+  fi
+
+  if [ -d /mnt/system ]; then
+    SYSMOUNT="/mnt/system"
+  elif [ -d /system_root ]; then
+    SYSMOUNT="/system_root"
+  else
+    SYSMOUNT="/system"
+  fi
+
+  export S=$SYSMOUNT/system
+}
+
+mount_system() {
+  mount -t $SYSFS $SYSDEV $SYSMOUNT -o rw,discard
+}
+
+unmount_system() {
+  umount $SYSMOUNT
+}
+
+determine_system_mount
+
 case "$1" in
   backup)
+    mount_system
     mkdir -p $C
     if check_prereq; then
         if check_whitelist system; then
+            unmount_system
             exit 127
         fi
     fi
@@ -107,10 +136,13 @@
     run_stage pre-backup
     run_stage backup
     run_stage post-backup
+    unmount_system
   ;;
   restore)
+    mount_system
     if check_prereq; then
         if check_whitelist tmp; then
+            unmount_system
             exit 127
         fi
     fi
@@ -121,6 +153,7 @@
     restore_addon_d
     rm -rf $C
     sync
+    unmount_system
   ;;
   *)
     echo "Usage: $0 {backup|restore}"