#!/bin/sh

echo "Press q to enter command prompt"

global autoboot_timeout
global.autoboot_timeout=1

timeout -a $global.autoboot_timeout -v key
autoboot="$?"

if [ "${key}" = "q" ]; then
	exit
fi

if [ -z "${nv.myboot}" ]; then
	nv myboot=mmc
	saveenv
fi

if [ $global.board.dip = 08 ] || [ $nv.myboot = usb ]; then
	# init USB subsystem
	usb
fi

# turn mPCIe on
gpio_direction_output 100 1

# export MTD partition table
global of_partition_binding="legacy"

# check if USB drive is available
if [ -e /dev/disk0.0 ]; then
	mount /dev/disk0.0
	if [ -e /mnt/disk0.0/kernel-fit.itb ]; then
		echo "Booting from USB (disk0.0)"
		global linux.bootargs.base="root=/dev/sda2 rootwait"
		bootm /mnt/disk0.0/kernel-fit.itb@conf$global.board.id@1
		if [ $? -ne 0 ]; then
			bootm /mnt/disk0.0/kernel-fit.itb
		fi
	fi
fi

# check if USB (second partition) is available
if [ -e /dev/disk0.1 ]; then
	mount /dev/disk0.1
	if [ -e /mnt/disk0.1/boot/kernel-fit.itb ]; then
		echo "Booting from USB (disk0.1)"
		global linux.bootargs.base="root=/dev/sda2 rootwait"
		bootm /mnt/disk0.1/boot/kernel-fit.itb@conf$global.board.id@1
		if [ $? -ne 0 ]; then
			bootm /mnt/disk0.1/boot/kernel-fit.itb
		fi
	fi
fi

if [ $nv.myboot != nand ]; then
	# check if MMC is available
	if [ -e /dev/mmc0.0 ]; then
		mount /dev/mmc0.0
		if [ -e /mnt/mmc0.0/kernel-fit.itb ]; then
			echo "Booting from MMC (mmc0.0)"
			global linux.bootargs.base="root=/dev/mmcblk0p2 rootwait"
			bootm /mnt/mmc0.0/kernel-fit.itb@conf$global.board.id@1
			if [ $? -ne 0 ]; then
				bootm /mnt/mmc0.0/kernel-fit.itb
			fi
		fi
	fi

	# check if MMC (second partition) is available
	if [ -e /dev/mmc0.1 ]; then
		mount /dev/mmc0.1
		if [ -e /mnt/mmc0.1/boot/kernel-fit.itb ]; then
			echo "Booting from MMC (mmc0.1)"
			global linux.bootargs.base="root=/dev/mmcblk0p2 rootwait"
			bootm /mnt/mmc0.1/boot/kernel-fit.itb@conf$global.board.id@1
			if [ $? -ne 0 ]; then
				bootm /mnt/mmc0.1/boot/kernel-fit.itb
			fi
		fi
	fi
fi

# boot from NAND
echo "Booting from NAND"
ubiattach /dev/nand0.UBI
mount /dev/nand0.UBI.ubi.kernel
if [ ! -e /mnt/nand0.UBI.ubi.kernel/mininit-syspart ]; then
	filetype -s img_type /mnt/nand0.UBI.ubi.kernel/kernel-fit.itb
	if [ $img_type = dtb ]; then
		echo "Boot legacy kernel"
		global linux.bootargs.base="root=ubi0:kernel rw ubi.mtd=5 rootfstype=ubifs rootwait init=/init"
		bootm /mnt/nand0.UBI.ubi.kernel/kernel-fit.itb@conf$global.board.id@1
	else
		echo "Performing initial update"
		cp /mnt/nand0.UBI.ubi.kernel/kernel-fit.itb /tmp
		umount /mnt/nand0.UBI.ubi.kernel/
		ubiupdatevol /dev/nand0.UBI.ubi.kernel /tmp/kernel-fit.itb
		mount /dev/nand0.UBI.ubi.kernel
	fi
fi
global linux.bootargs.base="root=ubi0:kernel rw ubi.mtd=5 rootfstype=ubifs rootwait init=/mininit-syspart"
bootm /mnt/nand0.UBI.ubi.kernel/kernel-fit.itb@conf$global.board.id@1
if [ $? -ne 0 ]; then
	bootm /mnt/nand0.UBI.ubi.kernel/kernel-fit.itb
fi
