#!/sbin/sh
# AnyKernel2 Backend
# osm0sis @ xda-developers

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;
ui_print " ----- |   | ----       ";
ui_print "   |   |___| |             ";
ui_print "   |   |   | |    _        ";
ui_print "   |   |   | |___|         ";

/sbin/busybox mount /system;

if [ "$(file_getprop /tmp/anykernel/anykernel.sh do.devicecheck)" == 1 ]; then
  ui_print "Checking device...";
  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 "Unsupported device. Aborting...";
  fi;
fi;

if [ "$(file_getprop /tmp/anykernel/anykernel.sh do.initd)" == 1 ]; then
  ui_print "Creating init.d...";
  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
  ui_print "Pushing System files...";
  cp -fr /tmp/anykernel/system/* /system/;
fi;

ui_print "TheRagingBeast Kernel 15/10/17 Nightly";
ui_print "By ~TheHardGamer_V@RuN"
/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.cleanup)" == 1 ]; then
  rm -rf /tmp/anykernel;
fi;

umount /system;
ui_print " ";
ui_print "Done!";
ui_print " ";

