#
# Custom U-Boot environment for Nerves
#

#
# 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;\
    if test ${nerves_fw_active} = "a"; then\
        setenv uenv_root /dev/mmcblk2p1;\
        setenv bootpart 2:1;\
    else\
        setenv uenv_root /dev/mmcblk2p2;\
        setenv bootpart 2:2;\
    fi

#
# Default Linux commandline:
#
cmdline=coherent_pool=1M quiet

# Defaults
console=ttymxc1,115200n8
bootdir=/boot
bootfile=Image
fdtdir=/boot
fdtfile=iot-gate-imx8plus.dtb
devtype=mmc

# Memory offset for loading files
initrd_addr=0x43800000
initrd_high=0xffffffffffffffff
fdt_addr_r=0x43000000
fdt_addr=0x43000000
loadaddr=0x40480000

# Helper functions
set_bootargs=\
    setenv bootargs console=${console} root=${uenv_root} rootfstype=squashfs rootwait ro ${cmdline};

load_image=\
    load ${devtype} ${bootpart} ${loadaddr} ${bootdir}/${bootfile};

load_fdt=\
    echo loading ${fdtdir}/${fdtfile}...;\
    load ${devtype} ${bootpart} ${fdt_addr_r} ${fdtdir}/${fdtfile};

boot_mmc=\
    run set_bootargs;\
    booti ${loadaddr} - ${fdt_addr};

# Boot
bootcmd=run nerves_init load_image load_fdt boot_mmc
