#!/sbin/sh
# Kernel Flasher installer backend

tmp=/tmp/kernel-flasher

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
	umount /system
}

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

setperm() {
	find "$3" -type d -exec chmod "$1" {} \;
	find "$3" -type f -exec chmod "$2" {} \;
}

mount() {
	mountpoint -q "$1" || /sbin/busybox mount -o rw "$1" || abort "Unable to mount $1 as rw!"
	>> "$1/.rw" && return || /sbin/busybox mount -o remount,rw "$1"
	>> "$1/.rw" && return || abort "Unable to write to $1!"
}

umount() {
	mountpoint -q "$1" || return 0
	rm -f "$1/.rw"
	/sbin/busybox umount "$1"
}

print "#######################################"
print "#           kernel flasher            #"
print "#      by jcadduono, version 5.1      #"
print "#   add your own intro message here!  #"
print "#######################################"

# Unpack the installer
[ "$zip" ] && {
	print "Unpacking the installer..."
	extract "$zip" "$tmp"
}
cd "$tmp"

. config.sh

[ "$device_names" ] && {
	if ! command -v getprop; then
		print "Warning: getprop not found! Skipping device check!"
		return
	fi
	print "Checking device compatibility..."
	match=0
	ro_product_device=$(getprop ro.product.device)
	ro_product_model=$(getprop ro.product.model)
	ro_build_product=$(getprop ro.build.product)
	for i in $device_names; do
		[ "$ro_product_device" = "$i" ] ||
		[ "$ro_product_model" = "$i" ] ||
		[ "$ro_build_product" = "$i" ] &&
			match=1
	done
	[ $match != 1 ] && abort "Unsupported device"
}

mount /system
# mount /data

setperm 0755 0755 "$bin"

print "Running boot image patcher..."
sh boot-patcher.sh || abort

print "Boot image patching complete"

cleanup
print "Done installing!"
