#!/sbin/sh
# Unroot script by brigudav

getvar() {
  local VARNAME=$1
  local VALUE=$(eval echo \$"$VARNAME");
  for FILE in /data/.supersu /system/.supersu; do
    if [ -z "$VALUE" ]; then
      LINE=$(cat $FILE 2>/dev/null | grep "$VARNAME=")
      if [ ! -z "$LINE" ]; then
        VALUE=${LINE#*=}
      fi
    fi
  done
  eval $VARNAME=\$VALUE
}

readlink /proc/$$/fd/$OUTFD 2>/dev/null | grep /tmp >/dev/null
if [ "$?" -eq "0" ]; then
  # rerouted to log file, we don't want our ui_print commands going there
  OUTFD=0

  # we are probably running in embedded mode, see if we can find the right fd
  # we know the fd is a pipe and that the parent updater may have been started as
  # 'update-binary 3 fd zipfile'
  for FD in `ls /proc/$$/fd`; do
    readlink /proc/$$/fd/$FD 2>/dev/null | grep pipe >/dev/null
    if [ "$?" -eq "0" ]; then
      ps | grep " 3 $FD " | grep -v grep >/dev/null
      if [ "$?" -eq "0" ]; then
        OUTFD=$FD
        break
      fi
    fi
  done
fi

#ui_print() {
#  echo -n -e "ui_print $1\n" >> /proc/self/fd/$OUTFD
#  echo -n -e "ui_print\n" >> /proc/self/fd/$OUTFD
#}

ch_con() {
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toybox chcon -h u:object_r:system_file:s0 $1 1>/dev/null 2>/dev/null
  LD_LIBRARY_PATH=$SYSTEMLIB /system/toolbox chcon -h u:object_r:system_file:s0 $1 1>/dev/null 2>/dev/null
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toolbox chcon -h u:object_r:system_file:s0 $1 1>/dev/null 2>/dev/null
  chcon -h u:object_r:system_file:s0 $1 1>/dev/null 2>/dev/null
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toybox chcon u:object_r:system_file:s0 $1 1>/dev/null 2>/dev/null
  LD_LIBRARY_PATH=$SYSTEMLIB /system/toolbox chcon u:object_r:system_file:s0 $1 1>/dev/null 2>/dev/null
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toolbox chcon u:object_r:system_file:s0 $1 1>/dev/null 2>/dev/null
  chcon u:object_r:system_file:s0 $1 1>/dev/null 2>/dev/null
}

ch_con_ext() {
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toybox chcon $2 $1 1>/dev/null 2>/dev/null
  LD_LIBRARY_PATH=$SYSTEMLIB /system/toolbox chcon $2 $1 1>/dev/null 2>/dev/null
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toolbox chcon $2 $1 1>/dev/null 2>/dev/null
  chcon $2 $1 1>/dev/null 2>/dev/null
}

ln_con() {
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toybox ln -s $1 $2 1>/dev/null 2>/dev/null
  LD_LIBRARY_PATH=$SYSTEMLIB /system/toolbox ln -s $1 $2 1>/dev/null 2>/dev/null
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toolbox ln -s $1 $2 1>/dev/null 2>/dev/null
  ln -s $1 $2 1>/dev/null 2>/dev/null
  ch_con $2 1>/dev/null 2>/dev/null
}

set_perm() {
  chown $1.$2 $4
  chown $1:$2 $4
  chmod $3 $4
  ch_con $4
  ch_con_ext $4 $5
}

cp_perm() {
  rm $5
  if [ -f "$4" ]; then
    cat $4 > $5
    set_perm $1 $2 $3 $5 $6
  fi
}

mv_perm() {
  rm $5
  if [ -f "$4" ]; then
    mv $4 $5
    set_perm $1 $2 $3 $5 $6
  fi
}

is_mounted() {
  if [ ! -z "$2" ]; then
    cat /proc/mounts | grep $1 | grep $2, >/dev/null
  else
    cat /proc/mounts | grep $1 >/dev/null
  fi
  return $?
}

toolbox_mount() {
  RW=rw
  if [ ! -z "$2" ]; then
    RW=$2
  fi

  DEV=
  POINT=
  FS=
  for i in `cat /etc/fstab | grep "$1"`; do
    if [ -z "$DEV" ]; then
      DEV=$i
    elif [ -z "$POINT" ]; then
      POINT=$i
    elif [ -z "$FS" ]; then
      FS=$i
      break
    fi
  done
  if (! is_mounted $1 $RW); then mount -t $FS -o $RW $DEV $POINT; fi
  if (! is_mounted $1 $RW); then mount -t $FS -o $RW,remount $DEV $POINT; fi

  DEV=
  POINT=
  FS=
  for i in `cat /etc/recovery.fstab | grep "$1"`; do
    if [ -z "$POINT" ]; then
      POINT=$i
    elif [ -z "$FS" ]; then
      FS=$i
    elif [ -z "$DEV" ]; then
      DEV=$i
      break
    fi
  done
  if [ "$FS" = "emmc" ]; then
    if (! is_mounted $1 $RW); then mount -t ext4 -o $RW $DEV $POINT; fi
    if (! is_mounted $1 $RW); then mount -t ext4 -o $RW,remount $DEV $POINT; fi
    if (! is_mounted $1 $RW); then mount -t f2fs -o $RW $DEV $POINT; fi
    if (! is_mounted $1 $RW); then mount -t f2fs -o $RW,remount $DEV $POINT; fi
  else
    if (! is_mounted $1 $RW); then mount -t $FS -o $RW $DEV $POINT; fi
    if (! is_mounted $1 $RW); then mount -t $FS -o $RW,remount $DEV $POINT; fi
  fi
}

remount_system_rw() {
  if (! is_mounted /system rw); then mount -o rw,remount /system; fi
  if (! is_mounted /system rw); then mount -o rw,remount /system /system; fi
  if (! is_mounted /system rw); then toolbox_mount /system; fi
}

# 'readlink -f' is not reliable across devices/recoveries, this works for our case
resolve_link() {
  local RESOLVE=$1
  local RESOLVED=
  while (true); do
    RESOLVED=$(readlink $RESOLVE || echo $RESOLVE)
    if [ "$RESOLVE" = "$RESOLVED" ]; then
      echo $RESOLVE
      break
    else
      RESOLVE=$RESOLVED
    fi
  done
}

wipe_system_files_if_present() {
  GO=false
  SYSTEMFILES="
    /system/xbin/daemonsu
    /system/xbin/sugote
    /system/xbin/sugote-mksh
    /system/xbin/supolicy
    /system/xbin/ku.sud
    /system/xbin/.ku
    /system/xbin/.su
    /system/lib/libsupol.so
    /system/lib64/libsupol.so
    /system/bin/.ext/.su
    /system/etc/init.d/99SuperSUDaemon
    /system/etc/.installed_su_daemon
    /system/app/Superuser.apk
    /system/app/Superuser.odex
    /system/app/Superuser
    /system/app/SuperUser.apk
    /system/app/SuperUser.odex
    /system/app/SuperUser
    /system/app/superuser.apk
    /system/app/superuser.odex
    /system/app/superuser
    /system/app/Supersu.apk
    /system/app/Supersu.odex
    /system/app/Supersu
    /system/app/SuperSU.apk
    /system/app/SuperSU.odex
    /system/app/SuperSU
    /system/app/supersu.apk
    /system/app/supersu.odex
    /system/app/supersu
    /system/app/VenomSuperUser.apk
    /system/app/VenomSuperUser.odex
    /system/app/VenomSuperUser
  "
  for FILE in $SYSTEMFILES; do
    if [ -d "$FILE" ]; then GO=true; fi
    if [ -f "$FILE" ]; then GO=true; fi
  done

  RMSU=false
  if (! $RWSYSTEM); then
    if [ -f "/system/xbin/su" ]; then
      # only remove /system/xbin/su if it's SuperSU. Could be firmware-included version, we
      # do not want to cause remount for that
      SUPERSU_CHECK=$(cat /system/xbin/su | grep SuperSU)
      if [ $? -eq 0 ]; then
        GO=true
        RMSU=true
      fi
    fi

    SPECIALSYSTEMFILES="
      /system/etc/install-recovery_original.sh
      /system/bin/install-recovery_original.sh
      /system/bin/app_process32_original
      /system/bin/app_process32_exposed
      /system/bin/app_process64_original
      /system/bin/app_process64_exposed
      /system/bin/app_process_init
    "
    for FILE in $SPECIALSYSTEMFILES; do
      if [ -d "$FILE" ]; then GO=true; fi
    done
  fi

  if ($GO); then
    if (! $RWSYSTEM); then
      echo "- Remounting system r/w :("
      remount_system_rw
    fi

    for FILE in $SYSTEMFILES; do
      if [ -d "$FILE" ]; then rm -rf $FILE; fi
      if [ -f "$FILE" ]; then rm -f $FILE; fi
    done

    if (! $RWSYSTEM); then
      # remove wrongly placed /system/xbin/su as well
      if ($RMSU); then
        rm -f /system/xbin/su
      fi

      # Restore install-recovery and app_process from system install
      # Otherwise, our system-less install will fail to boot
      if [ -f "/system/etc/install-recovery_original.sh" ]; then
        rm -f /system/etc/install-recovery.sh
        mv /system/etc/install-recovery_original.sh /system/etc/install-recovery.sh
      fi
      if [ -f "/system/bin/install-recovery_original.sh" ]; then
        rm -f /system/bin/install-recovery.sh
        mv /system/bin/install-recovery_original.sh /system/bin/install-recovery.sh
      fi
      if [ -f "/system/bin/app_process64_original" ]; then
        rm -f /system/bin/app_process64
        if [ -f "/system/bin/app_process64_xposed" ]; then
          ln -s /system/bin/app_process64_xposed /system/bin/app_process64
        else
          mv /system/bin/app_process64_original /system/bin/app_process64
        fi
      fi
      if [ -f "/system/bin/app_process32_original" ]; then
        rm -f /system/bin/app_process32
        if [ -f "/system/bin/app_process32_xposed" ]; then
          ln -s /system/bin/app_process32_xposed /system/bin/app_process32
        else
          mv /system/bin/app_process32_original /system/bin/app_process32
        fi
      fi
      if [ -f "/system/bin/app_process64" ]; then
        rm /system/bin/app_process
        ln -s /system/bin/app_process64 /system/bin/app_process
      elif [ -f "/system/bin/app_process32" ]; then
        rm /system/bin/app_process
        ln -s /system/bin/app_process32 /system/bin/app_process
      fi
      rm -f /system/bin/app_process_init
    fi
  fi
}

wipe_data_competitors_and_cache() {
  rm -f /data/dalvik-cache/*com.noshufou.android.su*
  rm -f /data/dalvik-cache/*/*com.noshufou.android.su*
  rm -f /data/dalvik-cache/*com.koushikdutta.superuser*
  rm -f /data/dalvik-cache/*/*com.koushikdutta.superuser*
  rm -f /data/dalvik-cache/*com.mgyun.shua.su*
  rm -f /data/dalvik-cache/*/*com.mgyun.shua.su*
  rm -f /data/dalvik-cache/*com.m0narx.su*
  rm -f /data/dalvik-cache/*/*com.m0narx.su*
  rm -f /data/dalvik-cache/*com.kingroot.kinguser*
  rm -f /data/dalvik-cache/*/*com.kingroot.kinguser*
  rm -f /data/dalvik-cache/*com.kingroot.master*
  rm -f /data/dalvik-cache/*/*com.kingroot.master*
  rm -f /data/dalvik-cache/*me.phh.superuser*
  rm -f /data/dalvik-cache/*/*me.phh.superuser*
  rm -f /data/dalvik-cache/*Superuser.apk*
  rm -f /data/dalvik-cache/*/*Superuser.apk*
  rm -f /data/dalvik-cache/*SuperUser.apk*
  rm -f /data/dalvik-cache/*/*SuperUser.apk*
  rm -f /data/dalvik-cache/*superuser.apk*
  rm -f /data/dalvik-cache/*/*superuser.apk*
  rm -f /data/dalvik-cache/*VenomSuperUser.apk*
  rm -f /data/dalvik-cache/*/*VenomSuperUser.apk*
  rm -f /data/dalvik-cache/*eu.chainfire.supersu*
  rm -f /data/dalvik-cache/*/*eu.chainfire.supersu*
  rm -f /data/dalvik-cache/*Supersu.apk*
  rm -f /data/dalvik-cache/*/*Supersu.apk*
  rm -f /data/dalvik-cache/*SuperSU.apk*
  rm -f /data/dalvik-cache/*/*SuperSU.apk*
  rm -f /data/dalvik-cache/*supersu.apk*
  rm -f /data/dalvik-cache/*/*supersu.apk*
  rm -f /data/dalvik-cache/*.oat
  rm -rf /data/app/com.noshufou.android.su*
  rm -rf /data/app/com.koushikdutta.superuser*
  rm -rf /data/app/com.mgyun.shua.su*
  rm -rf /data/app/com.m0narx.su*
  rm -rf /data/app/com.kingroot.kinguser*
  rm -rf /data/app/com.kingroot.master*
  rm -rf /data/app/me.phh.superuser*
}

# check_zero "progress_message" "success message" "failure message" "command"
check_zero() {
  if ($CONTINUE); then
    if [ ! -z "$1" ]; then echo "$1"; fi
    eval "$4"
    if [ $? -eq 0 ]; then
      if [ ! -z "$2" ]; then echo "$2"; fi
    else
      if [ ! -z "$3" ]; then echo "$3"; fi
      CONTINUE=false
    fi
  fi
}

# check_zero_def "progress message" "command"
check_zero_def() {
  check_zero "$1" "" "--- Failure, aborting" "$2"
}

# find boot image partition if not set already
find_boot_image() {
  # expand the detection if we find more, instead of reading from fstab, because unroot
  # from the SuperSU APK doesn't have the fstab to read from
  if [ -z "$BOOTIMAGE" ]; then
    for PARTITION in kern-a KERN-A android_boot ANDROID_BOOT kernel KERNEL boot BOOT lnx LNX; do
      BOOTIMAGE=$(readlink /dev/block/by-name/$PARTITION || readlink /dev/block/platform/*/by-name/$PARTITION || readlink /dev/block/platform/*/*/by-name/$PARTITION)
      if [ ! -z "$BOOTIMAGE" ]; then break; fi
    done
  fi
}

# use only on 6.0+, tries to read current boot image and detect if we can do a system install
# without any boot image patching. Requirements:
# - /data readable
# - not pre-patched by SuperSU
# - dm-verity disabled
# - init loads from /data/security/current/sepolicy
# - sepolicy has init load_policy or permissive init
# It symlink/patches the relevant files to /data, and sets SYSTEMLESS variable if not already set
detect_systemless_required() {
  OLD_SYSTEMLESS=$SYSTEMLESS
  if [ "$OLD_SYSTEMLESS" = "detect" ]; then
    # we don't override a pre-set true/false value
    SYSTEMLESS=true
  fi

  # check /data mounted
  if (! is_mounted /data); then
    return
  fi

  # find boot image partition
  find_boot_image

  CONTINUE=true
  if [ -z "$BOOTIMAGE" ]; then
    # no boot image partition detected, abort
    return
  fi

  # extract ramdisk from boot image
  rm -rf /sutmp
  mkdir /sutmp

  check_zero "" "" "" "LD_LIBRARY_PATH=$RAMDISKLIB $BIN/sukernel --bootimg-extract-ramdisk $BOOTIMAGE /sutmp/ramdisk.packed"
  check_zero "" "" "" "LD_LIBRARY_PATH=$RAMDISKLIB $BIN/sukernel --ungzip /sutmp/ramdisk.packed /sutmp/ramdisk"
  if (! $CONTINUE); then return; fi

  # detect SuperSU patch
  LD_LIBRARY_PATH=$RAMDISKLIB $BIN/sukernel --patch-test /sutmp/ramdisk
  if [ $? -ne 0 ]; then
    return
  fi

  # detect dm-verity in use
  for i in `LD_LIBRARY_PATH=$RAMDISKLIB $BIN/sukernel --cpio-ls /sutmp/ramdisk | grep fstab`; do
    rm -f /sutmp/fstab

    check_zero "" "" "" "LD_LIBRARY_PATH=$RAMDISKLIB $BIN/sukernel --cpio-extract /sutmp/ramdisk $i /sutmp/fstab"
    if (! $CONTINUE); then return; fi

    VERIFY=$(cat /sutmp/fstab | grep verify | grep system)
    if [ $? -eq 0 ]; then
      # verify flag found, dm-verity probably enabled, modifying /system may prevent boot
      return
    fi
  done

  # detect init loading from /data/security/current/sepolicy
  check_zero "" "" "" "LD_LIBRARY_PATH=$RAMDISKLIB $BIN/sukernel --cpio-extract /sutmp/ramdisk init /sutmp/init"
  if (! $CONTINUE); then return; fi

  CURRENT=$(cat /sutmp/init | grep "/data/security/current/sepolicy")
  if [ $? -ne 0 ]; then
    # this init doesn't load from the default sepolicy override location
    return
  fi

  # extract sepolicy
  check_zero "" "" "" "LD_LIBRARY_PATH=$RAMDISKLIB $BIN/sukernel --cpio-extract /sutmp/ramdisk sepolicy /sutmp/sepolicy"
  if (! $CONTINUE); then return; fi

  GO=false

  # detect init permissive
  if (! $GO); then
    INIT_PERMISSIVE=$(LD_LIBRARY_PATH=$RAMDISKLIB $BIN/supolicy --dumpav /sutmp/sepolicy | grep "[TYPE]" | grep " init (PERMISSIVE) ")
    if [ $? -eq 0 ]; then
      GO=true
    fi
  fi

  # detect init load_policy
  if (! $GO); then
    INIT_LOAD_POLICY=$(LD_LIBRARY_PATH=$RAMDISKLIB $BIN/supolicy --dumpav /sutmp/sepolicy | grep "[AV]" | grep " ALLOW " | grep " init-->kernel (security) " | grep "load_policy")
    if [ $? -eq 0 ]; then
      GO=true
    fi
  fi

  # copy files to /data
  if (! $GO); then return; fi

  rm -rf /data/security/*
  mkdir /data/security/current
  set_perm 1000 1000 0755 /data/security/current u:object_r:security_file:s0

  LD_LIBRARY_PATH=$RAMDISKLIB $BIN/supolicy --file /sutmp/sepolicy /data/security/current/sepolicy
  set_perm 1000 1000 0644 /data/security/current/sepolicy u:object_r:security_file:s0

  for i in seapp_contexts file_contexts file_contexts.bin property_contexts service_contexts selinux_version; do
    ln -s /$i /data/security/current/$i
  done

  ln -s /system/etc/security/mac_permissions.xml /data/security/current/mac_permissions.xml

  # if we reach this point, we can do a system install
  if [ "$OLD_SYSTEMLESS" = "detect" ]; then
    # we don't override a pre-set true/false value
    SYSTEMLESS=false
  fi
}

echo " "
echo "*****************"
echo "SuperSU uninstaller"
echo "*****************"

echo "- Mounting /system, /data and rootfs"

mount -o ro /system
toolbox_mount /system ro
mount /data
toolbox_mount /data
mount -o rw,remount /
mount -o rw,remount / /

if [ -z "$BIN" ]; then
  # TWRP went full retard
  if [ ! -f "/sbin/unzip" ]; then
    echo "- BAD RECOVERY DETECTED, NO UNZIP, ABORTING"
    exit 1
  fi
fi

if [ -z "$NOOVERRIDE" ]; then
  # read override variables
  getvar SYSTEMLESS
  getvar PATCHBOOTIMAGE
  getvar BOOTIMAGE
  getvar STOCKBOOTIMAGE
  getvar BINDSYSTEMXBIN
  getvar PERMISSIVE
fi
if [ -z "$SYSTEMLESS" ]; then
  # detect if we need systemless, based on Android version and boot image
  SYSTEMLESS=detect
fi
if [ -z "$PATCHBOOTIMAGE" ]; then
  # only if we end up doing a system-less install
  PATCHBOOTIMAGE=true
fi
if [ -z "$BINDSYSTEMXBIN" ]; then
  # causes launch_daemonsu to bind over /system/xbin, disabled by default
  BINDSYSTEMXBIN=false
fi
if [ -z "$PERMISSIVE" ]; then
  # don't make everything fake-permissive
  PERMISSIVE=false
fi

API=$(cat /system/build.prop | grep "ro.build.version.sdk=" | dd bs=1 skip=21 count=2)
ABI=$(cat /system/build.prop /default.prop | grep -m 1 "ro.product.cpu.abi=" | dd bs=1 skip=19 count=3)
ABILONG=$(cat /system/build.prop /default.prop | grep -m 1 "ro.product.cpu.abi=" | dd bs=1 skip=19)
ABI2=$(cat /system/build.prop /default.prop | grep -m 1 "ro.product.cpu.abi2=" | dd bs=1 skip=20 count=3)
SUMOD=06755
SUGOTE=false
SUPOLICY=false
INSTALL_RECOVERY_CONTEXT=u:object_r:system_file:s0
MKSH=/system/bin/mksh
PIE=
SU=su
ARCH=arm
APKFOLDER=false
APKNAME=/system/app/Superuser.apk
APPPROCESS=false
APPPROCESS64=false
SYSTEMLIB=/system/lib
RAMDISKLIB=$SYSTEMLIB
RWSYSTEM=true

if [ "$API" -le "21" ]; then
  # needed for some intermediate AOSP verions

  remount_system_rw

  cat /system/bin/toolbox > /system/toolbox
  chmod 0755 /system/toolbox
  ch_con /system/toolbox
fi

if [ "$ABI" = "x86" ]; then ARCH=x86; fi;
if [ "$ABI2" = "x86" ]; then ARCH=x86; fi;
if [ "$API" -eq "$API" ]; then
  if [ "$API" -ge "17" ]; then
    SUGOTE=true
    PIE=.pie
    if [ "$ARCH" = "x86" ]; then SU=su.pie; fi;
    if [ "$ABILONG" = "armeabi-v7a" ]; then ARCH=armv7; fi;
    if [ "$ABI" = "mip" ]; then ARCH=mips; fi;
    if [ "$ABILONG" = "mips" ]; then ARCH=mips; fi;
  fi
  if [ "$API" -ge "18" ]; then
    SUMOD=0755
  fi
  if [ "$API" -ge "20" ]; then
    if [ "$ABILONG" = "arm64-v8a" ]; then ARCH=arm64; SYSTEMLIB=/system/lib64; APPPROCESS64=true; fi;
    if [ "$ABILONG" = "mips64" ]; then ARCH=mips64; SYSTEMLIB=/system/lib64; APPPROCESS64=true; fi;
    if [ "$ABILONG" = "x86_64" ]; then ARCH=x64; SYSTEMLIB=/system/lib64; APPPROCESS64=true; fi;
    APKFOLDER=true
    APKNAME=/system/app/SuperSU/SuperSU.apk
  fi
  if [ "$API" -ge "19" ]; then
    SUPOLICY=true
    if [ "$(LD_LIBRARY_PATH=$SYSTEMLIB /system/toolbox ls -lZ /system/bin/toolbox | grep toolbox_exec > /dev/null; echo $?)" -eq "0" ]; then
      INSTALL_RECOVERY_CONTEXT=u:object_r:toolbox_exec:s0
    fi
  fi
  if [ "$API" -ge "21" ]; then
    APPPROCESS=true
  fi
  if [ "$API" -ge "22" ]; then
    SUGOTE=false
  fi
fi
if [ ! -f $MKSH ]; then
  MKSH=/system/bin/sh
fi

#echo "DBG [$API] [$ABI] [$ABI2] [$ABILONG] [$ARCH] [$MKSH]"

# Don't extract in TWRP
#if [ -z "$BIN" ]; then
#  echo "- Extracting files"

#  cd /tmp
#  mkdir supersu
#  cd supersu

#  unzip -o "$ZIP"

  BIN=/supersu
  COM=/supersu
#fi

# execute binaries from ramdisk
chmod 0755 $BIN/*
RAMDISKLIB=$BIN:$SYSTEMLIB

if [ "$API" -ge "19" ]; then
  # 4.4+: permissive all teh things
  LD_LIBRARY_PATH=$RAMDISKLIB $BIN/supolicy --live "permissive *"
fi

SAMSUNG=false
if [ "$API" -eq "$API" ]; then
  SAMSUNG_CHECK=$(cat /system/build.prop | grep "ro.build.fingerprint=" | grep -i "samsung")
  if [ $? -eq 0 ]; then
    SAMSUNG=true
  fi

  if [ "$API" -ge "23" ]; then
    # 6.0+
    echo "- Detecting system compatibility"
    detect_systemless_required

    if ($SYSTEMLESS); then
      RWSYSTEM=false
    fi
  elif [ "$API" -ge "22" ]; then
    if [ "$SYSTEMLESS" = "detect" ]; then
      SYSTEMLESS=true
    fi

    # 5.1/Samsung
    if ($SYSTEMLESS); then
      if ($SAMSUNG); then
        RWSYSTEM=false
      fi
    fi
  fi
fi

# Do not use SYSTEMLESS after this point, but refer to RWSYSTEM

if ($RWSYSTEM); then
  echo "- System mode"

  remount_system_rw

  echo "- Disabling OTA survival"
  chmod 0755 $BIN/chattr$PIE
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/bin/su
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/xbin/su
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/bin/.ext/.su
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/sbin/su
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /vendor/sbin/su
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /vendor/bin/su
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /vendor/xbin/su
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/xbin/daemonsu
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/xbin/sugote
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/xbin/sugote_mksh
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/xbin/supolicy
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/xbin/ku.sud
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/xbin/.ku
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/xbin/.su
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/lib/libsupol.so
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/lib64/libsupol.so
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/etc/install-recovery.sh
  LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -ia /system/bin/install-recovery.sh

  echo "- Removing files"

  rm -f /system/bin/su
  rm -f /system/xbin/su
  rm -f /system/sbin/su
  rm -f /vendor/sbin/su
  rm -f /vendor/bin/su
  rm -f /vendor/xbin/su

  rm -rf /data/app/eu.chainfire.supersu-*
  rm -rf /data/app/eu.chainfire.supersu.apk

  wipe_system_files_if_present
  wipe_data_competitors_and_cache

  rm /data/su.img
  rm /cache/su.img

  echo "- Placing files"

  if [ -f "/system/bin/app_process32_original" ]; then
    rm -f /system/bin/app_process
    rm -f /system/bin/app_process_init
    mv_perm 0 2000 0755 /system/bin/app_process32_original /system/bin/app_process32 u:object_r:zygote_exec:s0
    ln -s app_process32 /system/bin/app_process
  fi

  if [ -f "/system/bin/app_process64_original" ]; then
    rm -f /system/bin/app_process
    rm -f /system/bin/app_process_init
    mv_perm 0 2000 0755 /system/bin/app_process64_original /system/bin/app_process64 u:object_r:zygote_exec:s0
    ln -s app_process64 /system/bin/app_process
  fi

  if [ -f "/system/etc/install-recovery_original.sh" ]; then
    mv_perm 0 0 0544 /system/etc/install-recovery_original.sh /system/etc/install-recovery.sh
  fi

  if [ -f "/system/bin/install-recovery_original.sh" ]; then
    mv_perm 0 0 0750 /system/bin/install-recovery_original.sh /system/bin/install-recovery.sh u:object_r:install_recovery_exec:s0
  fi

  rm /system/toybox
  rm /system/toolbox
else
  echo "- System-less mode, boot image support required"
  
  echo "- Removing old files"

  rm -f /system/bin/su
  rm -f /system/xbin/su
  rm -f /system/sbin/su
  rm -f /vendor/sbin/su
  rm -f /vendor/bin/su
  rm -f /vendor/xbin/su

  rm -rf /data/app/eu.chainfire.supersu-*
  rm -rf /data/app/eu.chainfire.supersu.apk

  wipe_system_files_if_present
  wipe_data_competitors_and_cache

  rm -f /data/su.img
  rm -f /cache/su.img
  
  echo "- Creating paths"

  mkdir /su
  mkdir /su/bin
  set_perm 0 0 0755 /su/bin
  
  echo "- Placing files"
  
    rm -rf /sutmp
    mkdir /sutmp
    cp_perm 0 0 0755 $BIN/sukernel /su/bin/sukernel
  
    check_zero_def "- Extracting ramdisk" "LD_LIBRARY_PATH=$SYSTEMLIB /su/bin/sukernel --bootimg-extract-ramdisk $BOOTIMAGE /sutmp/ramdisk.packed"
    check_zero_def "- Decompressing ramdisk" "LD_LIBRARY_PATH=$SYSTEMLIB /su/bin/sukernel --ungzip /sutmp/ramdisk.packed /sutmp/ramdisk"

    if ($CONTINUE); then
      echo "- Checking patch status"
      LD_LIBRARY_PATH=$SYSTEMLIB /su/bin/sukernel --patch-test /sutmp/ramdisk
      if [ $? -ne 0 ]; then
        echo "--- Already patched, attempting to find stock backup"

        if ($CONTINUE); then
          LD_LIBRARY_PATH=$SYSTEMLIB /su/bin/sukernel --restore /sutmp/ramdisk /sutmp/stock_boot.img
          if [ $? -ne 0 ]; then
            echo "--- Restore failed, aborting"
            echo "- Unmounting /system"
            umount /system
            exit 1
          else
            echo "--- Backup restored"
            STOCKBOOTIMAGE=/sutmp/stock_boot.img
            echo "- Flashing stock boot image"
            dd if=$STOCKBOOTIMAGE of=$BOOTIMAGE bs=4096
            echo "- Remove tmp files"
            rm -rf /su
            rm -rf /sutmp
            rm -f /data/stock_boot_*.img
            rm -f /data/stock_boot_*.img.gz
            rm -f /cache/stock_boot_*.img
            rm -f /cache/stock_boot_*.img.gz
          fi
        fi
      fi
   fi

fi

echo "- Unmounting /system"
umount /system

echo "- Done !"
exit 0
