# default values
setenv load_addr "0x45000000"
setenv overlay_error "false"
setenv verbosity "1"
setenv console "both"
setenv bootlogo "false"
setenv overlay_prefix "sun50i-a64"
setenv recovery "false"
setenv recovery_image "recovery-pinephone.cpio.lz4.u-boot"
setenv kernel = "Image.gz"

echo "Boot script loaded from ${devtype}"

if test -e ${devtype} ${devnum} diya-config.txt; then
    echo "Loading environment variables from ${devtype} ${devnum} diya-config.txt"
    load ${devtype} ${devnum} ${load_addr} diya-config.txt
    env import -t ${load_addr} ${filesize}
fi

if test "${console}" = "display" || test "${console}" = "both"; then setenv consoleargs "console=ttyS0,115200 console=tty0"; fi
if test "${console}" = "serial"; then setenv consoleargs "console=ttyS0,115200"; fi
if test "${bootlogo}" = "true"; then
        setenv consoleargs "splash plymouth.ignore-serial-consoles ${consoleargs}"
else
        setenv consoleargs "splash=verbose ${consoleargs}"
fi


echo "Loading kernel FDT from ${devtype} ${devnum} ${fdtfile}"
load ${devtype} ${devnum} ${fdt_addr_r} ${fdtfile}
fdt addr ${fdt_addr_r}
fdt resize 65536
for overlay_file in ${overlays}; do
    if load ${devtype} ${devnum} ${load_addr} allwinner/overlay/${overlay_prefix}-${overlay_file}.dtbo; then
        echo "Applying kernel provided DT overlay ${overlay_prefix}-${overlay_file}.dtbo"
        fdt apply ${load_addr} || setenv overlay_error "true"
    fi
done

if test "${overlay_error}" = "true"; then
    echo "Error applying DT overlays, restoring original DT"
    load ${devtype} ${devnum} ${fdt_addr_r} ${fdtfile}
fi


echo "Loading kernel from ${devtype} ${devnum} ${kernel_comp_addr_r} ${kernel}"
load ${devtype} ${devnum} ${kernel_addr_r} ${kernel}
setenv kernel_comp_size ${filesize}
if test -e ${devtype} ${devnum} enable-recovery-mode; then
    echo "Booting Diya in recovery mode with ramdisk at ${devtype} ${devnum} ${ramdisk_addr_r} ${recovery_image}"
    fatrm ${devtype} ${devnum} enable-recovery-mode
    load ${devtype} ${devnum} ${ramdisk_addr_r} ${recovery_image}
    setenv bootargs "root=ramfs rootwait  ${consoleargs} ${extraargs} ${extraboardargs}"
    booti ${kernel_addr_r} ${ramdisk_addr_r} ${fdt_addr_r}
else
    # get PARTUUID of first partition on SD/eMMC it was loaded from
    # mmc 0 is always mapped to device u-boot (2016.09+) was loaded from
    if test "${devtype}" = "mmc"; then part uuid mmc 0:2 partuuid; fi
    setenv rootfstype "ext4"
    echo "Root dev PARTUUID is ${partuuid}"
    setenv bootargs "root=PARTUUID=${partuuid} rootwait rootfstype=${rootfstype} ${consoleargs} ${extraargs} ${extraboardargs}"
    echo "Booting Diya:  ${bootargs}"
    booti ${kernel_addr_r} - ${fdt_addr_r}
fi

# Recompile with:
# mkimage -C none -A arm -T script -d /boot/boot.cmd /boot/boot.scr
