#!/sbin/sh
# Copyright (C) 2018-2020 PitchBlack Recovery <pitchblackrecovery@gmail.com>
# Copyright (C) 2020 osm0sis, Dees_Troy and topjohnwu
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


OUTFD=/proc/self/fd/$2;
ZIPFILE="$3";

show_progress() { echo "progress $1 $2" > /proc/self/fd/$2; }
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; }

ui_print() {
  if $BOOTMODE; then
    echo "$1";
  else
    echo -e "ui_print $1\nui_print" >> $OUTFD;
  fi;
}
abort() { ui_print " "; ui_print "$1"; exit 1; }

# detect Magisk app/booted flashing
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;

# Const
IS_AB=true

show_progress 0.1000000, 0;
ui_print "|---------------------------------------------|";
ui_print "|---------------------------------------------|";
ui_print "|---------PitchBlack Recovery Project---------|";
ui_print "|-------------------v4.0----------------------|";
ui_print "|---------------------------------------------|";
ui_print "|---------------------------------------------|";
ui_print "|--------------Brought To You By--------------|";
ui_print "|---------------------------------------------|";
ui_print "|---------------PitchBlack Team---------------|";
ui_print "|---------------------------------------------|";
ui_print "|---------------------------------------------|";
ui_print "|            Based on TWRP v3.7.1_x           |";
ui_print "|---------------------------------------------|";

# /dev/tmp is safe for both booted and recovery installs
tmp=/dev/tmp/twrp-install;
partdir=/dev/block/bootdevice/by-name

if [ ! -d $partdir ]; then
  partdir=/dev/block/by-name
fi

if [ ! -d $partdir ]; then
  abort "Failed unable to find the partition!";
fi

# target partition without the slot suffix
if [ -e ${partdir}/recovery_b ] || [ "$IS_AB" == "false" ]; then
  target=${partdir}/recovery;
else
  target=${partdir}/boot;
fi;
name=$(basename $target);

ui_print "|-----------Unpacking the installer-----------|";
rm -rf $tmp;
mkdir -p $tmp;
unzip -o "$ZIPFILE" -d $tmp || abort "Failed to extract zip!";

cd $tmp;
recoverycpio=`(ls ramdisk-twrp.cpio || ls ramdisk-recovery.cpio) 2>/dev/null`;
recoveryimg=`(ls recovery.img) 2>/dev/null`;
[ "$recoverycpio" ] || [ "$recoveryimg" ] || abort "No TWRP ramdisk/image found in zip!";

tool=$tmp/magiskboot;
chmod 755 $tool;

ui_print "|---------------------------------------------|";
ui_print "|- Target:$target -|";
if [ "$IS_AB" == "false" ]; then
  cp -f $recoveryimg new-boot.img;
  blockdev --setrw $target;
  cat new-boot.img /dev/zero > $target 2>/dev/null || true;
  rm -f new-boot.img;
else
  for slot in _a _b; do
    ui_print "|------------Doing Work on slot $slot------------|";
    if [ "$recoverycpio" ]; then
      dd bs=1048576 if=$target$slot of=boot.img || abort "Failed to dump image!";
      $tool unpack -h boot.img || abort "Failed to unpack image!";

      # kernel string want_initramfs -> skip_initramfs (Magisk)
      $tool hexpatch kernel 77616E745F696E697472616D6673 736B69705F696E697472616D6673;
      # kernel string trip_initramfs -> skip_initramfs (SuperSU)
      $tool hexpatch kernel 747269705F696E697472616D6673 736B69705F696E697472616D6673;

      # boot.img header cmdline remove skip_override (flar2 patch)
      sed -i "s|$(grep '^cmdline=' header | cut -d= -f2-)|$(grep '^cmdline=' header | cut -d= -f2- | sed -e 's/skip_override//' -e 's/  */ /g' -e 's/[ \t]*$//')|" header;

      cp -f $recoverycpio ramdisk.cpio;
      $tool repack boot.img || abort "Failed to repack image!";
      $tool cleanup;
    else
      cp -f $recoveryimg new-boot.img;
    fi;

    blockdev --setrw $target$slot;
    cat new-boot.img /dev/zero > $target$slot 2>/dev/null || true;
    rm -f new-boot.img;
  done;
fi

#Copy Specific Files
ui_print "|---------------------------------------------|";
ui_print "|------------Unpacking The Tools--------------|";
if [ -f "/sdcard/PBRP" ]; then
cp -r $tmp/PBRP/tools /sdcard/PBRP/
else
mkdir -p /sdcard/PBRP
cp -r $tmp/PBRP/tools /sdcard/PBRP/
fi
ui_print "|--------Finished Unpacking The Tools---------|";

ui_print "|---------------------------------------------|";
ui_print "|---------------------------------------------|";
ui_print "|---------------------------------------------|";
ui_print "|---------------------------------------------|";
ui_print "|                  Thank You                  |";
if [[ ! -f "/sbin/keycheck" ]]; then
  ui_print "|   Reboot to PitchBlack Recovery Manually    |";
fi
ui_print "|---------------------------------------------|";
sleep 0.2s
show_progress 0.1000000, 90 ;
ui_print "|------------Installation finished!-----------|";

cd /;
rm -rf /dev/tmp;

