#!/bin/sh

PREREQ=""

prereqs() {
	echo "$PREREQ"
}

need_ethernet() {
		if [ -n "$(lsmod |egrep 'ixp400_eth|ixp4xx_npe|ixp4xx_eth')" ]; then
			return 0
		else
			return 1
		fi
}

pause_error() {
	#exit 1 # won't work; initramfs-tools ignores hook script exit code
	echo "" >&2
	if [ "$DEBIAN_FRONTEND" = "noninteractive" ] ; then
		echo "Unable to abort; system will probably be broken!" >&2
	else
		echo "Press Ctrl-C to abort build, or Enter to continue" >&2
		read
	fi
}

case $1 in
prereqs)
	prereqs
	exit 0
	;;
esac

. /usr/share/initramfs-tools/hook-functions

# The ethernet driver is ixp400_eth for 2.6.17 and below, which is a
# non-free driver that should be loaded if available. In 2.6.18, it
# became a free driver, ixp4xx_npe, that does not need to be included in
# the initramfs by default, but which needs some non-free firmware.
case "$version" in
2.6.1[1-7]*)
	manual_add_modules ixp400_eth
	if [ -n "$an_error_occured" ] || [ -z "$(find $DESTDIR \( -type f -or -type l \) | grep ixp400_eth)" ]; then
		echo "Warning: ixp400_eth ethernet driver not found, not included on image" >&2
		if need_ethernet; then
			echo "Warning: This system has the ethernet module loaded;" >&2
			echo "it's not safe to create an initramfs image that does not contain the module." >&2
			pause_error
		fi
	fi
;;
2.6.1[8-9]* | 2.6.20* | 2.6.2[1-3]*)
	if [ ! -e "/lib/firmware/NPE-B" ]; then
		echo "Warning: ixp4xx_npe ethernet driver firmware file /lib/firmware/NPE-B not found" >&2
		if need_ethernet; then
			for iface in $(route -n | grep "^0.0.0.0 " | grep UG | sed 's/.* //'); do
				if [ -n "$iface" ] && readlink /sys/class/net/"$iface"/device 2>/dev/null | grep -q ixp4xx_mac; then
					echo "Warning: This system is using the ixp4xx_mac ethernet module;" >&2
					echo "it's not safe to create an initramfs image for the new kernel" >&2
					echo "without the firmware file." >&2
					pause_error
				fi
			done
		fi
	fi
;;
*)
        if [ ! -e "/lib/firmware/NPE-B" ]; then
                echo "Warning: ixp4xx_eth ethernet driver firmware file /lib/firmware/NPE-B not found" >&2
                if need_ethernet; then
                        for iface in $(route -n | grep "^0.0.0.0 " | grep UG | sed 's/.* //'); do
                                if [ -n "$iface" ] && readlink /sys/class/net/"$iface"/device 2>/dev/null | grep -q ixp4xx_eth; then
                                        echo "Warning: This system is using the ixp4xx_eth ethernet module;" >&2
                                        echo "it's not safe to create an initramfs image for the new kernel" >&2
                                        echo "without the firmware file." >&2
                                        pause_error
                                fi
                        done
                fi
        fi
;;
esac

