#!/sbin/sh
# LazyFlasher installer backend (for helper functions only)

tmp=/tmp/twrp-install

if [ "$3" ]; then
	zip=$3
	console=/proc/$$/fd/$2
	# write the location of the console buffer to /tmp/console for other scripts to use
	echo "$console" > /tmp/console
else
	console=$(cat /tmp/console)
	[ "$console" ] || console=/proc/$$/fd/1
fi

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

abort() {
	[ "$1" ] && {
		print "Error: $1"
		print "Aborting..."
	}
	cleanup
	print "Failed to patch boot image!"
	exit 1
}

cleanup() {
	[ "$zip" ] && rm /tmp/console
}

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

print "#########################################"
print "#     TWRP installer for OnePlus 6      #"
print "#########################################"

# Unpack the installer
[ "$zip" ] && {
	print "Unpacking the installer..."
	extract "$zip" "$tmp"
}
cd "$tmp"
toolname="/magiskboot"
tool="$tmp$toolname"
targetfile="/boot.img"
target="$tmp$targetfile"

chmod 755 "$tool"

print "Running boot image patcher on slot A..."
dd if=/dev/block/bootdevice/by-name/boot_a "of=$target"
"$tool" --unpack boot.img
cp -f ramdisk-twrp.cpio ramdisk.cpio
"$tool" --repack boot.img
dd if=new-boot.img of=/dev/block/bootdevice/by-name/boot_a
rm boot.img
rm dtb
rm kernel
rm new-boot.img
rm ramdisk.cpio
print "Running boot image patcher on slot B..."
dd if=/dev/block/bootdevice/by-name/boot_b "of=$target"
"$tool" --unpack boot.img
cp -f ramdisk-twrp.cpio ramdisk.cpio
"$tool" --repack boot.img
dd if=new-boot.img of=/dev/block/bootdevice/by-name/boot_b

print "Boot image patching complete"

#cleanup
print "Done installing TWRP!"
