#!/bin/sh

path="$(wii-boot-path)"
layout="$(wii-boot-layout)"
instpath="/usr/lib/wii-linux/kernel"
ver="v7_2_10"

gumboot() {
	if ! [ -f "$path/gumboot/gumboot.lst" ]; then
		# huh, weirdo's probably not using Gumboot
		# at least give em a warning
		printf "\033[1;33m===> WARNING: \033[0mGumboot not detected, but new kernel file path added.\n"
		printf "\033[1;33m===> WARNING: \033[0mUnable to automatically update config file.\n"
		exit 0
	fi

	if command -v update-gumboot > /dev/null; then
		update-gumboot
	fi
}

npll() {
	if command -v update-npll > /dev/null; then
		update-npll
	fi
}

common() {
	if [ "$layout" = "legacy" ]; then
		# preserve the layout that Gumboot expects before invoking update-gumboot
		mkdir -p "$path/wiilinux"
		for ext in krn dtb txt; do
			cp "${instpath}/${ver}.${ext}" "$(wii-boot-path)/wiilinux/"
		done

		gumboot
	elif [ "$layout" = "npll" ]; then
		for ext in krn dtb txt; do
			cp "${instpath}/${ver}.${ext}" /boot/
		done

		npll
	else
		echo "Unknown layout \"$layout\"" >&2
	fi
}

post_install() {
	common
}

post_upgrade() {
	# FIXME: this algorithm isn't quite right for some older versions, but good enough, especially now that we have NPLL which can handle non-8.3 filenames, and not even being on FAT in the first place
	oldver="${2#*:}"
	oldver="v$(printf '%s' "${oldver%-*}" | tr '.' '_')"
	if [ "$oldver" != "$ver" ]; then
		case "$layout" in
			legacy) oldpath="$path/wiilinux" ;;
			npll) oldpath="/boot" ;;
			*) oldpath="" ;;
		esac
		if [ -n "$oldpath" ]; then
			for ext in krn dtb txt; do
				rm -f "$oldpath/$oldver.$ext"
			done
		fi
	fi
	common
}
