#!/sbin/sh
## [Magisk & recovery/TWRP] [boot-patcher] [This is standalone script, not sourced]
##
## AnyKernel3 Backend
##   Modified for NetHunter
##
## CREDITS to osm0sis @ xda-developers
##   REF: https://github.com/osm0sis/AnyKernel3/blob/376be8cd936e1f594939b8c653c03539bc2aa99b/META-INF/com/google/android/update-binary

#set -x

#------------------------------------------------------------------------------

# NetHuner additions
[ -f "/tmp/console" ] && OUTFD=$(cat /tmp/console);
[ "$OUTFD" ] || OUTFD=/proc/$$/fd/1;
ZIPFILE="$3";

BOOTMODE=false;
ps | grep zygote | grep -v grep >/dev/null && BOOTMODE=true;
$BOOTMODE || ps -A 2>/dev/null | grep zygote | grep -v grep >/dev/null && BOOTMODE=true;

DIR=/sdcard;
$BOOTMODE || DIR=$(dirname "$ZIPFILE");

TMPDIR=/dev/tmp
NN_DIR=$TMPDIR/nethunter/
TMP=$TMPDIR/nethunter/boot-patcher
[ "$AKHOME" ] || AKHOME=$TMP
[ "$ANDROID_ROOT" ] || ANDROID_ROOT=/system;

#------------------------------------------------------------------------------

ui_print() {
  until [ ! "$1" ]; do
    echo "ui_print $1
      ui_print" >> $OUTFD;
    shift;
  done;
}
ui_printfile() {
  while IFS='' read -r line || $BB [[ -n "$line" ]]; do
    ui_print "$line";
  done < $1;
}
show_progress() { echo "progress $1 $2" >> $OUTFD; }
file_getprop() { $BB grep "^$2=" "$1" | $BB cut -d= -f2-; }
find_slot() {
  local slot=$(getprop ro.boot.slot_suffix 2>/dev/null);
  [ "$slot" ] || slot=$($BB grep -o 'androidboot.slot_suffix=.*$' /proc/cmdline | $BB cut -d\  -f1 | $BB cut -d= -f2);
  if [ ! "$slot" ]; then
    slot=$(getprop ro.boot.slot 2>/dev/null);
    [ "$slot" ] || slot=$($BB grep -o 'androidboot.slot=.*$' /proc/cmdline | $BB cut -d\  -f1 | $BB cut -d= -f2);
    [ "$slot" ] && slot=_$slot;
  fi;
  [ "$slot" ] && echo "$slot";
}
setup_mountpoint() {
  [ -L $1 ] && $BB mv -f $1 ${1}_link;
  if [ ! -d $1 ]; then
    $BB rm -f $1;
    $BB mkdir -p $1;
  fi;
}
is_mounted() { $BB mount | $BB grep -q " $1 "; }
mount_apex() {
  [ -d /system_root/system/apex ] || return 1;
  local apex dest loop minorx num var;
  setup_mountpoint /apex;
  minorx=1;
  [ -e /dev/block/loop1 ] && minorx=$($BB ls -l /dev/block/loop1 | $BB awk '{ print $6 }');
  num=0;
  for apex in /system_root/system/apex/*; do
    dest=/apex/$($BB basename $apex .apex);
    case $dest in
      *.current|*.release) dest=$(echo $dest | $BB rev | $BB cut -d. -f2- | $BB rev);;
    esac;
    $BB mkdir -p $dest;
    case $apex in
      *.apex)
        $BB unzip -qo $apex apex_payload.img -d /apex;
        $BB mv -f /apex/apex_payload.img $dest.img;
        $BB mount -t ext4 -o ro,noatime $dest.img $dest 2>/dev/null;
        if [ $? != 0 ]; then
          while [ $num -lt 64 ]; do
            loop=/dev/block/loop$num;
            ($BB mknod $loop b 7 $((num * minorx));
            $BB losetup $loop $dest.img) 2>/dev/null;
            num=$((num + 1));
            $BB losetup $loop | $BB grep -q $dest.img && break;
          done;
          $BB mount -t ext4 -o ro,loop,noatime $loop $dest;
          if [ $? != 0 ]; then
            $BB losetup -d $loop 2>/dev/null;
          fi;
        fi;
      ;;
      *) $BB mount -o bind $apex $dest;;
    esac;
  done;
  [ -e /system_root/init.environ.rc ] && {
    for var in $($BB grep -o 'export .* /.*' /system_root/init.environ.rc | $BB awk '{ print $2 }'); do
      eval OLD_${var}=\$$var;
    done;
    $($BB grep -o 'export .* /.*' /system_root/init.environ.rc | $BB sed 's; /;=/;'); unset export;
  }
}
umount_apex() {
  [ -d /apex/com.android.runtime ] || return 1;
  local dest loop var;
  [ -e /system_root/init.environ.rc ] && {
    for var in $($BB grep -o 'export .* /.*' /system_root/init.environ.rc | $BB awk '{ print $2 }'); do
      if [ "$(eval echo \$OLD_$var)" ]; then
        eval $var=\$OLD_${var};
      else
        eval unset $var;
      fi;
      unset OLD_${var};
    done;
  }
  for dest in $($BB find /apex -type d -mindepth 1 -maxdepth 1); do
    if [ -f $dest.img ]; then
      loop=$($BB mount | $BB grep $dest | $BB cut -d\  -f1);
    fi;
    ($BB umount -l $dest;
    $BB losetup -d $loop) 2>/dev/null;
  done;
  $BB rm -rf /apex 2>/dev/null;
}
mount_all() {
  local byname mount slot system;
  echo "Mounting..." >&2;

  byname=bootdevice/by-name;
  [ -d /dev/block/$byname ] || byname=$(find /dev/block/platform -type d -name by-name 2>/dev/null | head -n1 | cut -d/ -f4-);
  [ -e /dev/block/$byname/super -a -d /dev/block/mapper ] && byname=mapper;
  [ -e /dev/block/$byname/system ] || slot=$(find_slot);
  for mount in /cache /data /metadata /persist; do
    if ! is_mounted $mount; then
      mount $mount 2>/dev/null && echo "$mount (fstab)" >&2 && UMOUNTLIST="$UMOUNTLIST $mount";
      if [ $? != 0 -a -e /dev/block/$byname$mount ]; then
        setup_mountpoint $mount;
        mount -o rw -t auto /dev/block/$byname$mount $mount && echo "$mount (direct)" >&2 && UMOUNTLIST="$UMOUNTLIST $mount";
      fi;
    fi;
  done;

  setup_mountpoint $ANDROID_ROOT;
  if ! is_mounted $ANDROID_ROOT; then
    mount -o rw -t auto $ANDROID_ROOT 2>/dev/null && echo "$ANDROID_ROOT (\$ANDROID_ROOT)" >&2;
  fi;
  case $ANDROID_ROOT in
    /system_root) setup_mountpoint /system;;
    /system)
      if ! is_mounted /system && ! is_mounted /system_root; then
        setup_mountpoint /system_root;
        mount -o rw -t auto /system_root && echo "/system_root (fstab)" >&2;
      elif [ -f /system/system/build.prop ]; then
        setup_mountpoint /system_root;
        mount --move /system /system_root && echo "/system_root (moved)" >&2;
      fi;
      if [ $? != 0 ]; then
        (umount /system;
        umount -l /system) 2>/dev/null;
        mount -o rw -t auto /dev/block/$byname/system$slot /system_root && echo "/system_root (direct)" >&2;
      fi;
    ;;
  esac;

  [ -f /system_root/system/build.prop ] && system=/system;
  for mount in /vendor /product /system_ext; do
    mount -o rw -t auto $mount 2>/dev/null && echo "$mount (fstab)" >&2;
    if [ $? != 0 ] && [ -L /system$mount -o -L /system_root$system$mount ]; then
      setup_mountpoint $mount;
      mount -o rw -t auto /dev/block/$byname$mount$slot $mount && echo "$mount (direct)" >&2;
    fi;
  done;

  if is_mounted /system_root; then
    mount_apex;
    mount -o bind /system_root$system /system && echo "/system (bind)" >&2;
  fi;

  echo " " >&2;
}
umount_all() {
  local mount;
  (if is_mounted /system; then
    $BB umount /system;
    $BB umount -l /system;
  fi) 2>/dev/null;
  umount_apex;
  (if [ -e /system_root ]; then
    $BB umount /system_root;
    $BB umount -l /system_root;
  fi;
  umount /vendor; # busybox umount /vendor breaks recovery on some hacky devices
  umount -l /vendor;
  for mount in /mnt/system /mnt/vendor /product /mnt/product /persist; do
    $BB umount $mount;
    $BB umount -l $mount;
  done;
  if is_mounted /data; then
    $BB umount /data;
    $BB umount -l /data;
  fi;
  if is_mounted /cache; then
    $BB umount /cache;
    $BB umount -l /cache;
  fi) 2>/dev/null;
}
setup_env() {
  $BB mount -o bind /dev/urandom /dev/random;
  if [ -L /etc ]; then
    setup_mountpoint /etc;
    $BB cp -af /etc_link/* /etc;
    $BB sed -i 's; / ; /system_root ;' /etc/fstab;
  fi;
  umount_all;
  ui_print "- Mounting Partitions";
  mount_all;
  OLD_LD_PATH=$LD_LIBRARY_PATH;
  OLD_LD_PRE=$LD_PRELOAD;
  OLD_LD_CFG=$LD_CONFIG_FILE;
  unset LD_LIBRARY_PATH LD_PRELOAD LD_CONFIG_FILE;
  if [ ! "$(getprop 2>/dev/null)" ]; then
    getprop() {
      local propdir propfile propval;
      for propdir in / /system_root /system /vendor /odm /product; do
        for propfile in default.prop build.prop; do
          if [ "$propval" ]; then
            break 2;
          else
            propval="$(file_getprop $propdir/$propfile $1 2>/dev/null)";
          fi;
        done;
      done;
      if [ "$propval" ]; then
        echo "$propval";
      else
        echo "";
      fi;
    }
  elif [ ! "$(getprop ro.build.type 2>/dev/null)" ]; then
    getprop() {
      ($(which getprop) | $BB grep "$1" | $BB cut -d[ -f3 | $BB cut -d] -f1) 2>/dev/null;
    }
  fi;
}
restore_env() {
  local dir;
  unset -f getprop;
  [ "$OLD_LD_PATH" ] && export LD_LIBRARY_PATH=$OLD_LD_PATH;
  [ "$OLD_LD_PRE" ] && export LD_PRELOAD=$OLD_LD_PRE;
  [ "$OLD_LD_CFG" ] && export LD_CONFIG_FILE=$OLD_LD_CFG;
  unset OLD_LD_PATH OLD_LD_PRE OLD_LD_CFG;
  umount_all;
  [ -L /etc_link ] && $BB rm -rf /etc/*;
  (for dir in /apex /system /system_root /etc; do
    if [ -L "${dir}_link" ]; then
      rmdir $dir;
      $BB mv -f ${dir}_link $dir;
    fi;
  done;
  $BB umount -l /dev/random) 2>/dev/null;
}
debugging() {
  case $(basename "$ZIPFILE" .zip) in
    *-debugging)
      ui_print " " "Creating debugging archive in $DIR...";
      [ -f /tmp/recovery.log ] && local log=/tmp/recovery.log;
      $BB tar -czf "$DIR/anykernel3-$(date +%Y-%m-%d_%H%M%S)-debug.tgz" $AKHOME $log;
    ;;
  esac;
}
cleanup() {
  cd $(dirname $AKHOME);
  rm -rf $AKHOME;
}
abort() {
  ui_print "$@";
  debugging;
  restore_env;
  if [ ! -f anykernel.sh -o "$(file_getprop anykernel.sh do.cleanuponabort 2>/dev/null)" == 1 ]; then
    cleanup;
  fi;
  exit 1;
}
do_devicecheck() {
  [ "$(file_getprop anykernel.sh do.devicecheck)" == 1 ] || return 1;
  local device devicename match product testname vendordevice vendorproduct;
  ui_print "- Checking device...";
  device=$(getprop ro.product.device 2>/dev/null);
  product=$(getprop ro.build.product 2>/dev/null);
  vendordevice=$(getprop ro.product.vendor.device 2>/dev/null);
  vendorproduct=$(getprop ro.vendor.product.device 2>/dev/null);
  for testname in $(file_getprop anykernel.sh 'device.name.*'); do
    for devicename in $device $product $vendordevice $vendorproduct; do
      if [ "$devicename" == "$testname" ]; then
        ui_print "- $testname";
        match=1;
        break 2;
      fi;
    done;
  done;
  if [ ! "$match" ]; then
    abort " " "Unsupported device. Aborting...";
  fi;
}
int2ver() {
  if $BB [ "$1" -eq "$1" ] 2>/dev/null; then
    echo "$1.0.0";
  elif [ ! "$(echo "$1" | $BB cut -d. -f3)" ]; then
    echo "$1.0";
  else
    echo "$1";
  fi;
}
do_versioncheck() {
  [ "$(file_getprop anykernel.sh supported.versions)" ] || return 1;
  local android_ver hi_ver lo_ver parsed_ver supported supported_ver;
  ui_print "- Checking Android version...";
  supported_ver=$(file_getprop anykernel.sh supported.versions | $BB tr -d '[:space:]');
  android_ver=$(file_getprop /system/build.prop ro.build.version.release);
  parsed_ver=$(int2ver $android_ver);
  if echo $supported_ver | $BB grep -q '-'; then
    lo_ver=$(int2ver "$(echo $supported_ver | $BB cut -d- -f1)");
    hi_ver=$(int2ver "$(echo $supported_ver | $BB cut -d- -f2)");
    if echo -e "$hi_ver\n$lo_ver\n$parsed_ver" | $BB sort -g | $BB grep -n "$parsed_ver" | $BB grep -q '^2:'; then
      supported=1;
    fi;
  else
    for ver in $(echo $supported_ver | $BB sed 's;,; ;g'); do
      if [ "$(int2ver $ver)" == "$parsed_ver" ]; then
        supported=1;
        break;
      fi;
    done;
  fi;
  if [ "$supported" ]; then
    ui_print "- $android_ver";
  else
    abort " " "Unsupported Android version. Aborting...";
  fi;
}
do_levelcheck() {
  [ "$(file_getprop anykernel.sh supported.patchlevels)" ] || return 1;
  local android_lvl hi_lvl lo_lvl parsed_lvl supported_lvl;
  ui_print "- Checking Android security patch level...";
  supported_lvl=$(file_getprop anykernel.sh supported.patchlevels | $BB grep -oE '[0-9]{4}-[0-9]{2}|-');
  android_lvl=$(file_getprop /system/build.prop ro.build.version.security_patch);
  parsed_lvl=$(echo $android_lvl | $BB grep -oE '[0-9]{4}-[0-9]{2}');
  if echo $supported_lvl | $BB grep -q '^\-'; then
    lo_lvl=0000-00;
    hi_lvl=$(echo $supported_lvl | $BB awk '{ print $2 }');
  elif echo $supported_lvl | $BB grep -q ' - '; then
    lo_lvl=$(echo $supported_lvl | $BB awk '{ print $1 }');
    hi_lvl=$(echo $supported_lvl | $BB awk '{ print $3 }');
  elif echo $supported_lvl | $BB grep -q '\-$'; then
    lo_lvl=$(echo $supported_lvl | $BB awk '{ print $1 }');
    hi_lvl=9999-99;
  fi;
  if echo -e "$hi_lvl\n$lo_lvl\n$parsed_lvl" | $BB sort -g | $BB grep -n "$parsed_lvl" | $BB grep -q '^2:'; then
    ui_print "- $android_lvl";
  else
    abort " " "Unsupported Android security patch level. Aborting...";
  fi;
}
dump_moduleinfo() {
cat <<EOF > $1;
name=AK3 Helper Module
version=$($BB awk '{ print $3 }' $AKHOME/vertmp) $($BB grep -oE '#.[0-9]' $AKHOME/vertmp)
versionCode=1
author=AnyKernel3
description=$KERNEL_STRING
EOF
}
dump_moduleremover() {
cat <<'EOF' > $1;
#!/system/bin/sh
MODDIR=${0%/*};
if [ "$(cat /proc/version)" != "$(cat $MODDIR/version)" ]; then
  rm -rf $MODDIR;
fi;
EOF
}
do_modules() {
  [ "$(file_getprop anykernel.sh do.modules)" == 1 ] || return 1;
  local block modcon moddir modtarget module slot umask;
  if [ "$(file_getprop anykernel.sh do.systemless)" == 1 ]; then
    cd $AKHOME/modules;
    ui_print "- Creating kernel helper Magisk module...";
    if [ -d /data/adb/magisk -a -f $AKHOME/split_img/.magisk ]; then
      umask=$(umask);
      umask 022;
      moddir=/data/adb/modules/ak3-helper;
      $BB rm -rf $moddir;
      mkdir -p system $moddir;
      ($BB mv -f product system;
      $BB mv -f vendor system) 2>/dev/null;
      $BB cp -rLf * $moddir;
      dump_moduleinfo $moddir/module.prop;
      dump_moduleremover $moddir/post-fs-data.sh;
      cp -f $AKHOME/vertmp $moddir/version;
      umask $umask;
    else
      ui_print "- Magisk installation not found. Skipped!";
    fi;
  else
    cd $AKHOME/modules;
    ui_print "- Pushing modules...";
    if [ -d /dev/block/mapper ]; then
      for block in system vendor; do
        for slot in "" _a _b; do
          $BB blockdev --setrw /dev/block/mapper/$block$slot 2>/dev/null;
        done;
      done;
    fi;
    if [ ! -d $NN_DIR ]; then
      $BB mount -o rw,remount -t auto /system;
      $BB mount -o rw,remount -t auto /vendor 2>/dev/null;
    fi;

    ## Adjusted for NetHunter: let's do a clean first and copy "modules.*" as well
    local do_clean=true

    for module in $(find . -name '*.ko' -o -name 'modules.*'); do
      modtarget=$(echo $module | $BB cut -c2-);
      ls /system_root
      if [ ! -e $modtarget ]; then
        case $module in
          */vendor/*) modcon=vendor;;
          *) modcon=system;;
        esac;
      fi;
      if is_mounted $modtarget; then
        $BB mount -o rw,remount -t auto $modtarget;
      fi;

      ## Adjusted for NetHunter: Remove old modules directories
      if [ "$do_clean" = true ]; then
        existing_moddir=$(echo $modtarget | $BB sed 's/lib\/modules\/.*$/lib\/modules\//')
        ui_print "- Removing existing modules directories in ${existing_moddir}";
        rm -rf ${existing_moddir}/../modules
        do_clean=false
      fi

      mkdir -p $(dirname $modtarget);
      $BB cp -rLf $module $modtarget;
      $BB chown 0:0 $modtarget;
      $BB chmod 644 $modtarget;
      if [ "$modcon" ]; then
        chcon "u:object_r:${modcon}_file:s0" $modtarget;
      fi;
      if is_mounted $modtarget; then
        $BB mount -o ro,remount -t auto $modtarget;
      fi;
    done;
    if [ ! -d $NN_DIR ]; then
      $BB mount -o ro,remount -t auto /system;
      $BB mount -o ro,remount -t auto /vendor 2>/dev/null;
    fi;
  fi;
  cd $AKHOME;
}

#------------------------------------------------------------------------------

mkdir -p $AKHOME/bin;
cd $AKHOME;

for ARCH32 in x86 arm; do
  if [ -d $AKHOME/tools/$ARCH32 ]; then
    BB=$AKHOME/tools/$ARCH32/busybox;
    chmod 755 $BB;
    $BB >/dev/null 2>&1;
    if [ $? == 0 ]; then
      $BB mv -f $AKHOME/tools/$ARCH32/* $AKHOME/tools;
      break;
    fi;
  fi;
done;
BB=$AKHOME/tools/busybox;
chmod 755 $BB;
$BB chmod -R 755 tools bin;
$BB --install -s bin;
if [ $? != 0 -o -z "$(ls bin)" ]; then
  abort "Busybox setup failed. Aborting...";
fi;

KERNEL_STRING="$(file_getprop anykernel.sh kernel.string)";
#ui_print "@ Kernel Script: $KERNEL_STRING";

if [ -f version ]; then
  ui_print "@ Found version"
  ui_print " ";
  ui_printfile version;
  ui_print " ";
fi;

ui_print "- AnyKernel3 by osm0sis @ xda-developers";

if [ -e "$NN_DIR/tools" ]; then
   restore_env;
fi;
setup_env;

do_devicecheck;
do_versioncheck;
do_levelcheck;

ui_print "- Installing...";
CORE=$($BB grep -oE 'ak.*core.sh' anykernel.sh);
[ -f tools/$CORE ] || $BB ln -s $AKHOME/tools/ak*-core.sh $AKHOME/tools/$CORE;
PATH="$AKHOME/bin:$PATH" home=$AKHOME $BB ash anykernel.sh $2 2>&1; # Spawn a new session (aka using sh), don't do it in the current session
if [ $? != 0 ]; then
  abort;
fi;

do_modules;

debugging;
restore_env;

if [ "$(file_getprop anykernel.sh do.cleanup)" == 1 ]; then
  cleanup;
fi;

ui_print "- AnyKernel complete"
