#!/sbin/sh
# LazyFlasher installer backend (for helper functions only)
# Heavily modified by Dees_Troy and osm0sis

tmp=/dev/tmp/twrp-install

# detect when flashing in Magisk Manager
ps | grep zygote | grep -v grep >/dev/null && BOOTMODE=true || BOOTMODE=false;
$BOOTMODE || ps -A 2>/dev/null | grep zygote | grep -v grep >/dev/null && BOOTMODE=true;

if [ "$3" ]; then
	zip=$3
	console=/proc/$$/fd/$2
fi

print() {
	if $BOOTMODE; then
		echo "$1"
	else
		if [ "$1" ]; then
			echo "ui_print $1" > "$console"
		else
			echo "ui_print  " > "$console"
		fi
	fi
}

extract() {
	rm -rf "$2"
	mkdir -p "$2"
	unzip -o "$1" -d "$2" || abort "Failed to extract zip to $2!"
}

print "########################################"
print "#    TWRP installer for A/B devices    #"
print "########################################"
print

# unpack the installer
[ "$zip" ] && {
	print "Unpacking the installer..."
	extract "$zip" "$tmp"
	print
}
cd "$tmp"
toolname="/magiskboot"
tool="$tmp$toolname"
targetfile="/boot.img"
target="$tmp$targetfile"
recoverycpio=`(ls ramdisk-twrp.cpio || ls ramdisk-recovery.cpio) 2>/dev/null`

chmod 755 "$tool"

for slot in a b; do
	print "Running boot image patcher on slot $slot..."
	dd if=/dev/block/bootdevice/by-name/boot_$slot "of=$target"
	"$tool" unpack -h boot.img

	# 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 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
	dd if=new-boot.img of=/dev/block/bootdevice/by-name/boot_$slot

	"$tool" cleanup
	rm -f new-boot.img
done

print
print "Boot image patching complete!"

cd /
rm -rf /dev/tmp

print
print "Done installing TWRP!"
print
print "*** NOTE: You are now unrooted! ***"
