#!/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 $* | $bb awk '{ print substr($0, index($0,$5)) }');
  for i in $dirs; do
    $bb 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; }
cleanup() { rm -rf /tmp/anykernel; }
if [ "$(file_getprop /tmp/anykernel/anykernel.sh do.cleanuponabort)" == 1 ]; then
    abort() { ui_print "$*"; cleanup; umount /system; umount /data; exit 1; }
  else
    abort() { ui_print "$*"; umount /system; umount /data; exit 1; }
fi;

show_progress 1.34 4;
ui_print " ";
cleanup;
mkdir -p /tmp/anykernel/bin;
cd /tmp/anykernel;
unzip -o "$ZIP";
if [ $? != 0 -o -z "$(ls /tmp/anykernel/tools)" ]; then
  abort "Unzip failed. Aborting...";
fi;
chmod -R 755 /tmp/anykernel/tools /tmp/anykernel/bin;
bb=/tmp/anykernel/tools/busybox;

ui_print " ";
ui_print "        Made using AnyKernel2 by osm0sis";
ui_print " ";
umount /system;
mount -o ro -t auto /system;
mount /data;
test -f /system/system/build.prop && root=/system;

ui_print "Injecting configurable Spectrum support...";
for i in $($bb --list); do
  $bb ln -s $bb /tmp/anykernel/bin/$i;
done;
if [ $? != 0 -o -z "$(ls /tmp/anykernel/bin)" ]; then
  abort "Recovery busybox setup failed. Aborting...";
fi;
PATH="/tmp/anykernel/bin:$PATH" $bb ash /tmp/anykernel/anykernel.sh $2;
if [ $? != "0" ]; then
  abort;
fi;

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

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