#
# Nerves variables
#

nerves_fw_active=a

# nerves_fw_autovalidate controls whether updates are considered valid once
# applied. If set to 0, the user needs to set nerves_fw_validated to 1 in their
# application. If they don't set it before a reboot, then the previous software
# is run. If 1, then no further action needs to be taken.
nerves_fw_autovalidate=1

# nerves_fw_validated is 1 if the current boot selection is accepted It is set
# to 1 here, since this environment is written in the factory, so it is
# implicitly valid.
nerves_fw_validated=1

# nerves_fw_booted is 0 for the first boot and 1 for all reboots after that.
# NOTE: Keep this '0' so that all new boards run a 'saveenv' to exercise the
#       code that writes back to the eMMC early on.
nerves_fw_booted=0

# The nerves initialization logic
#
# The nerves_init code is run at boot (see the last line of the file). It
# checks whether this is a first boot or not. If it's not the first boot, then
# the firmware better be validated or it reverts to running the firmware on
# the opposite partition.
nerves_revert=\
    if test ${nerves_fw_active} = "a"; then\
        echo "Reverting to partition B";\
        setenv nerves_fw_active "b";\
    else\
        echo "Reverting to partition A";\
        setenv nerves_fw_active "a";\
    fi

nerves_init=\
    if test ${nerves_fw_booted} = 1; then\
        if test ${nerves_fw_validated} = 0; then\
            run nerves_revert;\
            setenv nerves_fw_validated 1;\
            saveenv;\
        fi;\
    else\
        setenv nerves_fw_booted 1;\
        if test ${nerves_fw_autovalidate} = 1; then\
            setenv nerves_fw_validated 1;\
        fi;\
        saveenv;\
    fi;\
    setenv bootfile zImage.${nerves_fw_active};\
    if test ${nerves_fw_active} = "a"; then\
        setenv uenv_root /dev/mmcblk0p2;\
        setenv bootpart 0:2;\
    else\
        setenv uenv_root /dev/mmcblk0p3;\
        setenv bootpart 0:3;\
    fi

# Main Device Tree
fdtfile=/dtbs/at91-sama5d27_wlsom1_ek.dtb

console=ttyS0,115200
optargs=atmel.pm_modes=standby,ulp1 quiet

initrd_high=0xffffffff
fdt_high=0xffffffff
fdtovaddr=0x21800000
loadaddr=0x22000000
fdtaddr=0x21000000
video=0
kernel_bootpart=0:1

mmcargs=setenv bootargs console=${console} ${optargs} rootfstype=squashfs rootwait root=${uenv_root} rootwait video=${video}
loadzimage=load mmc ${kernel_bootpart} ${loadaddr} ${bootfile}
loadfdt=load mmc ${kernel_bootpart} ${fdtaddr} ${fdtfile}
mmcboot=echo Booting from mmc...;\
    run mmcargs;\
    bootz ${loadaddr} - ${fdtaddr}

bootcmd=run nerves_init loadzimage loadfdt mmcboot
