#!/sbin/sh

OUTFD=/proc/self/fd/$2;
ZIP="$3";
DIR=`dirname "$ZIP"`;

ui_print() {
  until [ ! "$1" ]; do
    echo -e "ui_print $1\nui_print" > $OUTFD;
    shift;
  done;
}
show_progress() { echo "progress $1 $2" > $OUTFD; }
set_perm_recursive() {
  dirs=$(echo $* | awk '{ print substr($0, index($0,$5)) }');
  for i in $dirs; do
    chown -R $1.$2 $i; chown -R $1:$2 $i;
    find "$i" -type d -exec chmod $3 {} +;
    find "$i" -type f -exec chmod $4 {} +;
  done;
}
file_getprop() { grep "^$2" "$1" | cut -d= -f2; }
getprop() { test -e /sbin/getprop && /sbin/getprop $1 || file_getprop /default.prop $1; }
abort() { ui_print "$*"; exit 1; }

show_progress 1.34 4;
ui_print " ";
mkdir -p /tmp/anykernel;
cd /tmp/anykernel;
unzip -o $ZIP;

/sbin/busybox mount /system;

if [ "$(file_getprop /tmp/anykernel/anykernel.sh do.devicecheck)" == 1 ]; then
  for i in 1 2 3 4 5; do
    testname="$(file_getprop /tmp/anykernel/anykernel.sh device.name$i)";
    if [ "$(getprop ro.product.device)" == "$testname" -o "$(getprop ro.build.product)" == "$testname" ]; then
      match=1;
    fi;
  done;
  if [ "$match" != 1 ]; then
    umount /system;
    abort "Its not REDMI 3S/PRIME... or REDMI 3X...";
  fi;
fi;

if [ "$(file_getprop /tmp/anykernel/anykernel.sh do.initd)" == 1 ]; then
  mkdir /system/etc/init.d;
  set_perm_recursive 0 0 0755 0755 /system/etc/init.d;
fi;

if [ "$(file_getprop /tmp/anykernel/anykernel.sh do.system)" == 1 ]; then
  cp -fr /tmp/anykernel/system/* /system/;
  set_perm_recursive 0 0 0777 0644 /system/etc/thermal-engine.conf;
  set_perm_recursive 0 0 0777 0777 /system/etc/init.d/exi;
fi;

/sbin/sh /tmp/anykernel/anykernel.sh;
if [ "$(cat /tmp/anykernel/exitcode)" == 1 ]; then
  umount /system;
  abort;
fi;

if [ "$(file_getprop /tmp/anykernel/anykernel.sh do.modules)" == 1 ]; then
  rm -rf /system/lib/modules;
  rm -rf /system/vendor/lib/hw/power.msm89*.so;
  rm -rf /system/vendor/lib64/hw/power.msm89*.so;
  mkdir /system/lib/modules;
  mkdir /system/lib/modules/pronto;
  set_perm_recursive 0 0 0755 0644 /system/lib/modules;
fi;

if [ "$(file_getprop /tmp/anykernel/anykernel.sh do.cleanup)" == 1 ]; then
  rm -rf /tmp/anykernel;
fi;

umount /system;