#!/bin/sh

# This code is covered by the GNU General Public License (GPLv2 or higher)

# 1) Check the files are okay

if [ ! -e kernel ]; then
	echo "You have to download the kernel file from the debian-installer for QNAP."
	exit 1
fi

if [ ! -e initrd.gz ]; then
	echo "You have to download the initrd.gz file from the debian-installer for QNAP."
	exit 1
fi

ifilesize=$(ls -l initrd.gz | awk '{print $5}')
# The ramdisk partition is 4 MB on the QNAP TS-109 and TS-209, and
# 9 MB on the QNAP TS-119, TS-219 and TS-219P.
if [ $ifilesize -ne 4194304 -a $ifilesize -ne 9437184 ]; then
	echo "The initrd.gz file is corrupt"
	exit 1
fi

# 2) Change the MAC address on QNAP TS-x10/TS-x19
uboot_mac() {
	ubootcfg -b 0 -f /dev/mtdblock4 -o - | grep "^ethaddr=" | sed "s/^ethaddr=//"
}

if [ $ifilesize -eq 9437184 ]; then
	if which iface_get_mac > /dev/null ; then
		eth0=$(iface_get_mac eth0)
	elif which get_mac > /dev/null ; then
		eth0=$(get_mac)
	fi
	if [ -z "$eth0" ]; then
		echo "Failed to obtain MAC address"
		exit 1
	fi
	if [ "$(uboot_mac)" != "$eth0" ]; then
		echo "Updating MAC address..."
		orig=$(ubootcfg -b 0 -f /dev/mtdblock4 -o - | grep -v "^eth" | cksum | cut -d " " -f 1)
		ubootcfg -b 0 -f /dev/mtdblock4 -o - | sed "s/^ethaddr=.*/ethaddr=$eth0/" > /tmp/debian.$$
		if which iface_get_mac > /dev/null ; then
			eth1=$(iface_get_mac eth1)
			if [ "$eth1" != "00:00:00:00:05:09" ]; then
				if ! grep -q "^eth1addr=" /tmp/debian.$$ ; then
					echo "eth1addr=$eth1" >> /tmp/debian.$$
				fi
			fi
		fi
		conf=$(grep -v "^eth" /tmp/debian.$$ | cksum | cut -d " " -f 1)
		if [ "$orig" != "$conf" -o "`cat /tmp/debian.$$`" == "" ]; then
			echo "Failed to generate new u-boot configuration."
			rm -f /tmp/debian.$$
			exit 1
		fi
		ubootcfg -b 0 -f /dev/mtdblock4 -i /tmp/debian.$$
		if [ "$?" != 0 ]; then
			echo "Error writing new configuration to flash.  Please check if your"
			echo "configuration looks correct with:"
			echo "    ubootcfg -b 0 -f /dev/mtdblock4 -o -"
			rm -f /tmp/debian.$$
			exit 1
		fi
		rm -f /tmp/debian.$$
	fi
	echo "Your MAC address is $(uboot_mac)"
	
fi

# 3) Finally, write the installer to flash
printf "Writing debian-installer to flash... "
cat kernel > /dev/mtdblock1
cat initrd.gz > /dev/mtdblock2
echo "done."
echo "Please reboot your QNAP device."