#!/bin/sh

#Turn led CPU1 on (PA0)
gpio_set_value 0 0

# V4: we boot with kernel and initramfs in both install and normal run
# Also, 4MB are enough for either (2M currently, but let's get some margin)
addpart /dev/ram0 4M@0x01000000(kernel)
addpart /dev/ram0 4M@0x01800000(initramfs)
# Also mem.kernel and mem.initrd, as we use both conventions, unfortunately
addpart /dev/mem  4M@0x71000000(kernel)
addpart /dev/mem  4M@0x71800000(initramfs)

# If we are in the flashing procedure, start with the kernel and file system
# pre-loaded into the DDR memory
memcmp -s /dev/mem -d /env/magicstr 0x717FFFF8 0x0 8
if [ $? -eq 0 ]; then
	echo "Booting kernel for NAND flashing procedure"
	dhcp 5
	bootargs="console=ttyS0,115200 panic=10"
	bootargs="$bootargs initrd=0x71800000,4M"
	bootargs="$bootargs root=/dev/ram0"
	bootargs="$bootargs SERVERIP=$eth0.serverip WRS_INSTALLING=y"
	bootargs="$bootargs ip=$eth0.ipaddr:$eth0.serverip:$eth0.gateway:$eth0.netmask:wrs:eth0"

	bootm /dev/ram0.kernel
fi

# Not installing: assume we have ubi in place: attach and mount it now,
# either it is used for booting, or an interactive user can see it
addpart /dev/nand0 511M@1M(ubi-nand)
ubiattach /dev/nand0.ubi-nand
mkdir /boot
mount /dev/ubi0.boot /boot
# we don't mount /usr and /update, although a user can do it as shown here
#    mkdir /usr; mount /dev/ubi0.usr /usr
#    mkdir /update; mount /dev/ubi0.update /update


#default value (can be overridden in /env/config)
preboot_timeout="0"
autoboot_timeout="5"
autoboot_select="1"

# Ethernet addresses are taken from sdb in hwinfo partition
addpart /dev/dataflash0 0x840@0x94800(hwinfo)
sdb set /dev/dataflash0.hwinfo             eth0.ethaddr
sdb set /dev/dataflash0.hwinfo wr0_ethaddr wr0.ethaddr
export wr0_ethaddr

### Override default value using /env/config (empty by default)
. /env/config
echo "Starting up barebox [wrs3] (MAC=$eth0.ethaddr WR_MAC=$wr0_ethaddr)"


### Generic setup
PATH=/env/bin
export PATH

if [ x$autoboot_timeout != x ]; then
    menu_timeout="-A $autoboot_timeout"
fi

#Set 2nd LED ON (PA1)
gpio_set_value 1 0

PS1="wrs-$eth0.ethaddr# "

# Create the menu
#menu -r -m boot
menu -a -m boot -d "Welcome on WRSv3 Boot Sequence"
menu -e -a -m boot -c 'boot-nand' -d "boot from nand (default)"
menu -e -a -m boot -c 'boot-script' -d "boot from TFTP script"
menu -e -a -m boot -c 'edit-config' -d "edit config"
menu -e -a -m boot -c 'exit 0' -d "exit to shell"
menu -e -a -m boot -c reset -d "reboot"

# allow the user to see previous messages
echo "starting menu in ${preboot_timeout} seconds"
sleep ${preboot_timeout}
# Select by default a specific menu
menu -m boot -S -n $autoboot_select
#Use a timeout to let the user change the entry in menu
menu -s boot $menu_timeout
