#!/usr/bin/env zsh

install_u-boot(){
	fn install_u-boot
	req=(strapdir disk_name efi_partitions swap_part_number rpool_name bpool_name root_name grub_mount)
	ckreq || return 1

	# When installing to metal we will install the os plus grub as usual and
	# then boot grub from u-boot written to SPI.
	# u-boot gets build as a part of the board definition in arm-sdk. We add
	# zfs support there in case we wish to boot the kernel directly later.

	# https://github.com/sigmaris/u-boot/wiki/RockPro64-boot-sequence

	# notice "installing u-boot to SPI."

	# The RK3399 Boot ROM will look for code with an ID block header for:
	# SPI flash 	at offset 0 bytes
	# eMMC 		at offset 0x8000 bytes (64 sectors, a sector is 0x200 bytes)
	# SDcard 	at offset 0x8000 bytes (64 sectors, a sector is 0x200 bytes)

	# this is where we write the idbloader.img (containing U-Boot TPL & SPL)

	# For SPI it must be written in rkspi format using the U-Boot mkimage tool.

	cat /proc/device-tree/model       # Pine64 RockPro64 v2.0
	cat /proc/device-tree/compatible  # pine64,rockpro64-v2.0pine64,rockpro64rockchip,rk3399

	cat /proc/mtd
	# dev:    size   erasesize  name
	# mtd0: 00060000 00001000 "u-boot-spl"
	# mtd1: 00398000 00001000 "u-boot"
	# mtd2: 00008000 00001000 "u-boot-env"
	# mtd3: 00c00000 00001000 "user"

	lsmtd
	# DEVICE MAJ:MIN NAME       TYPE SIZE
	# mtd0    90:0   u-boot-spl nor  384K
	# mtd1    90:2   u-boot     nor  3.6M
	# mtd2    90:4   u-boot-env nor   32K
	# mtd3    90:6   user       nor   12M

	mtdinfo
	# Count of MTD devices:           4
	# Present MTD devices:            mtd0, mtd1, mtd2, mtd3
	# Sysfs interface supported:      yes

	sudo mtdinfo /dev/mtd0
	# mtd0
	# Name:                           u-boot-spl
	# Type:                           nor
	# Eraseblock size:                4096 bytes, 4.0 KiB
	# Amount of eraseblocks:          96 (393216 bytes, 384.0 KiB)
	# Minimum input/output unit size: 1 byte
	# Sub-page size:                  1 byte
	# Character device major/minor:   90:0
	# Bad blocks are allowed:         false
	# Device is writable:             true

	sudo mtd_debug info /dev/mtd0
	# mtd.type = MTD_NORFLASH
	# mtd.flags = MTD_CAP_NORFLASH
	# mtd.size = 393216 (384K)
	# mtd.erasesize = 4096 (4K)
	# mtd.writesize = 1
	# mtd.oobsize = 0
	# regions = 0


build_atf(){
	fn build_atf
	req=(strapdir atf_branch atfgit compiler)
	ckreq || return 1

	notice "Build arm-trusted-firmware bl31.elf for rk3399."
	
	git config --global user.name 'Build Robot'
	git config --global user.email 'noemail@example.com'
	git clone --depth 1 -b "$atf_branch" "$atfgit" "$R/tmp/kernels/arm-trusted-firmware" || zerr
	pushd "$R/tmp/kernels/arm-trusted-firmware"
		#git am ../atf-rk3399-baudrate.patch
		make realclean
		make -j$(nproc) CROSS_COMPILE=$compile PLAT=rk3399 DEBUG=1 bl31 || zerr
	popd

	act "Publish arm-trusted-firmware bl31.elf"
	mkdir -p "$R/dist"
	cp "$R/tmp/kernels/arm-trusted-firmware/build/rk3399/debug/bl31/bl31.elf" "$R/dist"
}

build_uboot(){
	fn build_u-boot
	req=(strapdir ubootgit uboot_branch MAKEOPTS)
	ckreq || return 1

	defconfig=rockpro64-rk3399_defconfig
	img1type=rksd		# Rockchip SD Boot Image
	img1name=idbloader.img
	img2name=u-boot.itb
	artifact=u-boot
	
	notice "Build u-boot"
	"FIXME: AUTOBOOT was too chatty at the configure stage with these entries do its disabled for now."
	git clone --depth 1 "$ubootgit" -b "$uboot_branch" "$R/tmp/kernels/u-boot-rockpro64" || zer
	pushd  "$R/tmp/kernels/u-boot-rockpro64"
		make mrproper
		make $(defconfig)
		act "apply local changes to defconfig."
		"$R/tmp/kernels/rockpro64/rockpro64-linux/scripts/config" --file .config \
			--enable CONFIG_CMD_ZFS \
			--enable CONFIG_CMD_BOOTMENU \
			--enable CONFIG_MENU \
			--enable CONFIG_MENU_SHOW \
			--enable CONFIG_CFB_CONSOLE_ANSI \
			--enable CONFIG_CMD_BOOTEFI \
			--enable CONFIG_EFI_LOADER \
			--enable CONFIG_EFI_SECURE_BOOT \
			--enable CONFIG_CMD_BOOTM \
			--enable CONFIG_BOOTM_EFI \
			--enable CONFIG_BOOTM_LINUX \
			--enable CONFIG_BOOTM_NETBSD \
			--enable CONFIG_BLK \
			--enable CONFIG_VERSION_VARIABLE \
			--enable CONFIG_PARTITIONS \
			--enable CONFIG_DM_VIDEO 
			#--enable CONFIG_AUTOBOOT_KEYED \
			#--set-val CONFIG_BOOTDELAY 30 

		act "apply sigmaris changes to defconfig."
		"$R/tmp/kernels/rockpro64/rockpro64-linux/scripts/config" --file .config \
			--enable CONFIG_OF_BOARD_SETUP \
			--enable CONFIG_MTD \
			--enable CONFIG_CMD_MTDPARTS \
			--enable CONFIG_SPL_MMC \
			--enable CONFIG_SPL_SPI \
			--enable CONFIG_SPI_FLASH_MTD \
			--enable CONFIG_SPL_SPI_FLASH_SUPPORT \
			--enable CONFIG_NVME \
			--enable CONFIG_SCSI \
			--enable CONFIG_DM_SCSI \
			--enable CONFIG_OF_LIBFDT_OVERLAY \
			--enable CONFIG_FDT_FIXUP_PARTITIONS \
			--enable CONFIG_SERVERIP_FROM_PROXYDHCP \
			--enable CONFIG_AHCI \
			--enable CONFIG_SCSI_AHCI \
			--enable CONFIG_AHCI_PCI \
			--enable CONFIG_DM_KEYBOARD \
			--enable CONFIG_LED \
			--enable CONFIG_LED_GPIO \
			--set-val CONFIG_DEFAULT_DEVICE_TREE "rk3399-rockpro64" \
			--set-val CONFIG_SERVERIP_FROM_PROXYDHCP_DELAY_MS 100 \
			--set-val CONFIG_MTDIDS_DEFAULT "nor0=spi0.0" \
			--set-val CONFIG_MTDPARTS_DEFAULT="mtdparts=spi0.0:384k(u-boot-spl),3680k(u-boot),32k(u-boot-env),-(user)" 


		make -j$(nproc) $MAKEOPTS ARCH=arm CROSS_COMPILE=$compiler || zerr
		export BL31="$R/tmp/kernels/arm-trusted-firmware/build/rk3399/debug/bl31/bl31.elf"
		mkdir -p "$R/dist"

		act "create ${img1type}_${img1name} image file."
		"$R/tmp/kernels/u-boot-rockpro64/tools/mkimage" \
			-n rk3399 \						# set image name
			-T $(img1type) \					# set image type
			-d tpl/u-boot-tpl.bin:spl/u-boot-spl.bin \		# use image data from
			${img1type}_$(img1name)  # idbloader.img 
		act "Publish ${img1type}_${image1name}"
		cp ${img1type}_$(img1name) "$R/dist"

		img1type=rkspi		# Rockchip SPI Boot Image
		act "create ${img1type}_${img1name} image file."
		"$R/tmp/kernels/u-boot-rockpro64/tools/mkimage" \
			-n rk3399 \						# set image name
			-T $(img1type) \					# set image type
			-d tpl/u-boot-tpl.bin:spl/u-boot-spl.bin \		# use image data from
			${img1type}_$(img1name)  # idbloader.img 
		act "Publish ${img1type}_${image1name}"
		cp ${img1type}_$(img1name) "$R/dist"

		act "Publish ${image2name}"
		cp u-boot.itb "$R/dist"/$(img2name)  # u-boot.itb	
	popd
}

create_spi_image(){
	act "Create single SPI image with u-boot.itb at 0x60000"

	padsize=$((0x60000 - 1))
	img1size=$(wc -c <"$(img1name)")
	[ $img1size -le $padsize ] || exit 1
	dd \
		if=/dev/zero \
		of=$(img1name) \
		conv=notrunc \
		bs=1 \
		count=1 \
		seek=$padsize
	cat $(img1name) u-boot.itb > "$R/dist"/spi_combined.img
	create-u-boot-spi-scripts
	"$R/tmp/kernels/u-boot-rockpro64/tools/mkimage"	 \
		-C none \							# set compression
		-A arm \							# set architecture
		-T script \							# set image type
		-d scripts/flash_spi.cmd \					# use image data fro
		"$R/dist/flash_spi.scr"
}

spi_flash_img(){
	fn spi_flash_img
	req=(strapdir)
	ckreq || return 1

	notice "Create SD card image to flash u-boot to SPI"

        cp "$R/dist/flash_spi.scr boot.scr"
        cp "$R/dist/spi_combined.img spi_combined.img"
        dd \
		if=/dev/zero \
		of=boot.tmp \
		bs=1M \
		count=16
        mkfs.vfat -n u-boot-script boot.tmp
        mcopy -sm -i boot.tmp boot.scr ::
        mcopy -sm -i boot.tmp spi_combined.img ::
        dd \
		if=/dev/zero \
		of=flash_spi.img \
		bs=1M \
		count=32
        parted -s flash_spi.img mklabel gpt
        parted -s flash_spi.img unit s mkpart loader1 64 8063
        parted -s flash_spi.img unit s mkpart loader2 16384 24575
        parted -s flash_spi.img unit s mkpart boot fat16 24576 100%
        parted -s flash_spi.img set 3 legacy_boot on
        dd \
		if= "$R/tmp/kernels/u-boot-rockpro64/idbloader.img" \
		of=flash_spi.img \
		conv=notrunc \
		seek=64
        dd \
		if="$R/tmp/kernels/u-boot-rockpro6/u-boot.itb" \
		of=flash_spi.img \
		conv=notrunc \
		seek=16384
        dd \
		if=boot.tmp \
		of=flash_spi.img \
		conv=notrunc \
		seek=24576
        gzip flash_spi.img
}

set-bootloader(){
	fn set-bootloader
	req=(strapdir)
	ckreq || return 1

	case "$1" in
	    *-rockchip-rock64-*)
		SD_LOADER="$R/dist/rksd_loader.img"
		SPI_LOADER="$R/dist/rksd_loader.img"
		BOARD=rock64
		;;

	    *-rockchip-rockpro64-*)
		SD_LOADER="$R/dist/rksd_loader.img"
		SPI_LOADER="$R/dist/rkspi_loader.img"
		BOARD=rockpro64
		;;

	    *-rockchip-pinebookpro-*)
		SD_LOADER="$R/dist/rksd_loader.img"
		SPI_LOADER="$R/dist/rkspi_loader.img"
		BOARD=pinebookpro
		;;

	    *-rockchip-rockpi4b-*)
		SD_LOADER="$R/dist/rksd_loader.img"
		SPI_LOADER="$R/dist/rkspi_loader.img"
		BOARD=rockpi4b
		;;

	    *)
		echo "Cannot detect board from $1."
		exit 1
		;;
	esac

	if ! grep -qi "$BOARD" /proc/device-tree/compatible; then
	    echo "You are currently running on different board:"
	    echo "$(tr -d '\0' < /proc/device-tree/model || true)"
	    echo "It may brick your device or the system unless"
	    echo "you know what are you doing."
	    echo ""
	fi
}

bootloader-version(){
	fn bootloader-version
	req=(strapdir)
	ckreq || return 1

	# FIXME: Assumes partitions number p1 or p6 and uses p1 for both
	version() {
	    local DEVICE="${1/p6/p1}"

	    echo -n "Current version: "
	    if strings "$DEVICE" | grep "^U-Boot [a-z0-9.-]*$"; then
		echo -n "Board: "
		strings "$DEVICE" | grep -E "^board="
		echo -n "FDT: "
		strings "$DEVICE" | grep -E "^fdtfile="
	    else
		echo "not installed on $DEVICE."
	    fi
	    echo
	}
}

upgrade-sd-bootloader(){
	fn upgrade-sd-bootloader
	req=(strapdir SD_LOADER)
	ckreq || return 1

	notice "Upgrading pre-existing bootloader."
	# FIXME: 
	# extlinux, u-boot, grub, EFI
	# Assumes u-boot written to a mounted efi partion
	# Writes the rksd image only to a specific partition number on sd devices. Uses p1
	if [[ $(findmnt -M /boot/efi) ]]; then
		MNT_DEV=$(findmnt /boot/efi -n -o SOURCE)
	else
		echo "Error: efi partition not mounted."
		exit 1
	fi


	# report current version
	bootloader-version "$MNT_DEV"

	write_sd() {
	    case "$1" in
		/dev/mmcblk*p6|/dev/sd*p6|/dev/mapper/loop*p6|/dev/mapper/nvme*p6)
		    dd if="$2" of="${1/p6/p1}"
		    ;;

		*)
		    echo "Cannot detect boot device ($MNT_DEV)."
		    exit 1
		    ;;
	    esac
	}

	write_sd "$MNT_DEV" "$SD_LOADER"

	sync
}

erase-sd-bootloader(){
	fn erase-sd-bootloader
	req=(strapdir)
	ckreq || return 1

	notice "Erasing pre-existing bootloader."
	# FIXME: Writes/erases a specific partition number on sd devices. Uses p1
	MNT_DEV=$(findmnt /boot/efi -n -o SOURCE)

	# report current version
	bootloader-version "$MNT_DEV"

	write_sd() {
	    case "$1" in
		/dev/mmcblk*p6|/dev/sd*p6|/dev/mapper/loop*p6|/dev/mapper/nvme*p6)
		    dd \
			    if="$2" \
			    of="${1/p6/p1}"
		    ;;

		*)
		    echo "Cannot detect boot device ($MNT_DEV)."
		    exit 1
		    ;;
	    esac
	}

	write_sd "$MNT_DEV" "/dev/zero"

	sync
}

write-emmc-flash(){
	fn write-emmc-flash
	req=(strapdir)
	ckreq || return 1

	notice "Writing u-boot to emmc."
	for blkdevice in $(ls -d /dev/mmcblk* | sed -n -E '/mmcblk[0-9]+$/ p' ); do
	if [[ -f /sys/block/${blkdevice##*/}/device/type ]]; then
		if [[ $(< /sys/block/${blkdevice##*/}/device/type) == MMC ]]; then
			emmc_blkdevice=${blkdevice}
		fi
	fi
	done

	MNT_DEV=$(findmnt / -n -o SOURCE)	
	MNT_DEV=${MNT_DEV%p[0-9]*}	
	if [[ "$MNT_DEV" == $emmc_blkdevice* ]]; then
		echo "Cannot write when running from eMMC, use: $0 --force."
		exit 1
	fi	

	# When booting from sdcard:
	# the card appears as /dev/mmcblk1 and 
	# the emmc appears as /dev/mmcblk2	
	pushd "$R/tmp/kernels/u-boot-rockpro64"
		dd \
			if="$R/dist/rksd_idbloader.img" \
			of=/dev/${emmc_blkdevice} \
			seek=64
		dd \
			if="$R/dist/u-boot.itb" \
			of=/dev/${emmc_blkdevice} \
			seek=16384
	popd
}

erase-spi-flash(){
	fn erase-spi-flash
	req=(strapdir)
	ckreq || return 1

	notice "Erasing spi flash."
	# FIXME: Assumes contents of spi labels, we don't have 'loader' so fails.
	# mtd0: 00060000 00001000 "u-boot-spl"
	# mtd1: 00398000 00001000 "u-boot"
	# mtd2: 00008000 00001000 "u-boot-env"
	# mtd3: 00c00000 00001000 "user"
 
	if ! MTD=$(grep \"loader\" /proc/mtd | cut -d: -f1); then
	    echo "loader partition on MTD is not found"
	    return 1
	fi

	# report current version
	bootloader-version "/dev/${MTD/mtd/mtdblock}"

	flash_erase "/dev/$MTD" 0 0
}

write-spi-flash(){
	fn write-spi-flash
	req=(strapdir)
	ckreq || return 1

	notice "Writing spi flash."

	version "/dev/${MTD/mtd/mtdblock}"
	confirm

	write_nand() {
		if ! MTD=$(grep \"${1}\" /proc/mtd | cut -d: -f1); then
			echo "${1} partition on MTD is not found"
			exit 1
		fi
		echo "Writing /dev/$MTD with content of $2"
		flash_erase "/dev/$MTD" 0 0
		nandwrite "/dev/$MTD" < "$2"
	}
	write_nand u-boot-spl "$SPI_LOADER"
}


}

# u-boot menu has been deprecated, extlinux.conf is used instead and uutomatically
# updated with u-boot-update from u-boot-menu. see ARM-sdk/BOARDs/rockpro64-ayunfan.
create-u-boot-menu(){
	fn create-u-boot-menu
	req=(strapdir)
	ckreq || return 1
	
	# FIXME: Need to choose a default and fix the other calls
	cat <<-EOF | tee scripts/boot.cmd > /dev/null
		setenv bootmenu_0 Boot 1. kernel=bootm 0x82000000  	# Set first menu entry
		setenv bootmenu_1 Boot 2. kernel=bootm 0x83000000  	# Set second menu entry
		setenv bootmenu_2 Reset board=reset                	# Set third menu entry
		setenv bootmenu_3 U-Boot boot order=boot           	# Set fourth menu entry
		bootmenu 20        					# Run bootmenu with autoboot delay 20s

u-boot console command sequence:
from a android phone
		setenv bootmenu_0 "Boot LNX ARCH =
		setenv bootargs 'root=/dev/mmcblk0p7 rootfstype=ext4 rootwait'; \
		ext2load mmc 0:2 0x1000000 /boot/zImage; 
		ext2load mmc 0:2 0x2000000 /boot/tegra20-paz00.dtb; 
			bootz 0x1000000 - 0x2000000;"
pastbin example
		setenv bootargs 'mem=214M root=/dev/mmcblk0p2 noinitrd rw rootfstype=ext2 console=ttyS0,115200n8 rootwait'
		setenv kernelargs 'mem=214M root=/dev/mmcblk0p2 noinitrd rw rootfstype=ext2 console=ttyS0,115200n8 rootwait'
		saveenv
		display init force
		mmcinit 0
		fatload mmc 0 0 uzImage.bin
		textout -1 -1 \"Commands finished. Trying to boot...\" FFFFFF
		bootm 0

from fat partition
		fatload mmc 0 0x3000000 uImage
		fatload mmc 0 0x2A00000 devicetree.dtb
		bootm 0x3000000 - 0x2A00000

zfs support
		zfsload <interface> <dev[:part]> [addr]     [filename]             [bytes]
		zfsload mmc            2:2       0x30007fc0 /rpool/@/boot/uImage

grub from u-boot
		ext4load mmc 0:1 0x43300000 /boot/grub/arm-uboot/core.img
		bootm 0x43300000	

raspberrypi example
		setenv kernel_addr_r 2000000
		setenv fdt_addr_r 1000000
		setenv bootargs 'root=/dev/mmcblk0p7 rootfstype=ext4 rootwait'; \
		load mmc 0:2 \$kernel_addr_r /boot/image
		load mmc 0:2 \$fdt_addr_r boot/dtb/bcm2837-rpi-3-b.dtb

from the current spi
		setenv fdt_addr_r    0x01f00000
		setenv kernel_addr_r 0x02080000
		setenv devtype scsi
		setenv devnum 0
		setenv distro_bootpart 2
		
devuan-sdk version - variables set in arm-sdk-boards/(boardname>)
		setenv kernel_addr_z 0x44080000
                setenv kernel_addr_r 0x43000000
                setenv fdt_addr_r 0x42000000
                setenv ramdisk_addr_r 0x43300000
		setenv rootfsaddr 0x43300000
		setenv devtype mmc 
		setenv devnum 0 
		setenv distro_bootpart 1 
qemu changes
setenv console /dev/ttyS2
setenv root /dev/mmcblk0p2 
setenv root /dev/vda2
setenv bootargs "consoleblank=0 root=${root} rw rootwait console=${console},1500000n8 earlycon=uart8250,mmio32,0xff1a0000 console=tty1"
setenv bootargs "console=tty0 console=${console} root=/dev/mmcblk0p2 rw rootwait rootfstype=ext4 fbcon=rotate:1"
setenv bootargs "console=${console} root=/dev/vda2 mem=128M rdinit=/sbin/init"
setenv fdt_addr_r 0xf5f17000
setenv devtype virtio

if load ${devtype} ${devnum}:${distro_bootpart} ${kernel_addr_z} Image.gz; then
  unzip ${kernel_addr_z} ${kernel_addr_r}
if load ${devtype} ${devnum}:${distro_bootpart} ${fdt_addr_r} rk3399-rockpro64.dtb; then
  booti ${kernel_addr_r} - ${fdt_addr_r};
  fi;
fi

armbian: https://github.com/armbian/build/blob/master/config/bootscripts/boot-rockchip64.cmd

efi: https://github.com/ARM-software/u-boot/blob/master/doc/README.uefi
     https://u-boot.readthedocs.io/en/latest/develop/uefi/uefi.html
# the efi fat32 partition is mounted under /boot/efi 
load mmc 0:1 ${fdt_addr_r} rk3399-rockpro64.dtb
load mmc 0:1 ${kernel_addr_r} \
/EFI/Devuan\ daedalus\ \(RAID\ disk\ ata-WDC_WD30EZRZ-00WN9B0_WD-WCC4E6RKKRVX\)/grubaa64.efi
bootefi ${kernel_addr_r} ${fdt_addr_r}

# u-boot, extlinux.conf
label linux-5.0.0-rc3
kernel /Image
devicetree /sun50i-a64-amarula-relic.dtb
append console=ttyS0,115200 earlyprintk root=/dev/mmcblk0p2 rootwait rw

=> load mmc 0:2 ${fdt_addr_r} boot/dtb
29830 bytes read in 14 ms (2 MiB/s)
=> load mmc 0:1 ${kernel_addr_r} efi/debian/grubaa64.efi
reading efi/debian/grubaa64.efi
120832 bytes read in 7 ms (16.5 MiB/s)
=> bootefi ${kernel_addr_r} ${fdt_addr_r}

efi FIT:
=> load mmc 0:1 ${kernel_addr_r} image.fit
4620426 bytes read in 83 ms (53.1 MiB/s)
=> bootm ${kernel_addr_r}#config-grub-nofdt
## Loading kernel from FIT Image at 40400000 ...
   Using 'config-grub-nofdt' configuration
   Verifying Hash Integrity ... sha256,rsa2048:dev+ OK
   Trying 'efi-grub' kernel subimage
     Description:  GRUB EFI Firmware
     Created:      2019-11-20   8:18:16 UTC
     Type:         Kernel Image (no loading done)
     Compression:  uncompressed
     Data Start:   0x404000d0
     Data Size:    450560 Bytes = 440 KiB
     Hash algo:    sha256
     Hash value:   4dbee00021112df618f58b3f7cf5e1595533d543094064b9ce991e8b054a9eec
   Verifying Hash Integrity ... sha256+ OK
   XIP Kernel Image (no loading done)
## Transferring control to EFI (at address 404000d0) ...
Welcome to GRUB!

initramfs example https://armtix.artixlinux.org/info/firefly-rk3399.html
		mkimage -A arm -T ramdisk -d <path to initramfs> mkinitramfs-linux.uimg

		Next, you have to create u-boot script u-boot.cmd with following contents:

		setenv bootargs "consoleblank=0 root=${console} rw rootwait console=ttyS2,1500000n8 earlycon=uart8250,mmio32,0xff1a0000 console=tty1"
		load mmc 1:1 ${fdt_addr_r} /dtbs/rockchip/rk3399-firefly.dtb
		load mmc 1:1 ${kernel_addr_r} /Image
		load mmc 1:1 ${ramdisk_addr_r} /initramfs-linux.uimg
		booti ${kernel_addr_r} ${ramdisk_addr_r}:${filesize} ${fdt_addr_r}

		mkimage -A arm -T ramdisk -d boot.cmd boot.scr

	EOF

	"$R/tmp/kernels/u-boot-rockpro64/tools/mkimage" \
	-A arm \								# set architechture
	-O linux \								# set operating system	
	-T script \								# set image type
	-C none \								# set compression type
	-a 0 \									# set load address
	-e 0 \									# set entry point
	-n "ubootscript" \							# set image name
	-d scripts/boot.cmd \							# use image data from
	"$R/dist/boot.scr"

}

create-u-boot-spi-scripts(){
	fn create-u-boot-spi-scripts
	req=(strapdir)
	ckreq || return 1
	
	cat <<-'EOF' | tee "$R/tmp/kernels/u-boot-rockpro64/scripts/erase_spi.cmd" > /dev/null
		setenv blink_work 'led work on; sleep 0.1; led work off; sleep 0.1'
		setenv blink_diy 'led diy on; sleep 0.1; led diy off; sleep 0.1'

		echo "Enable SPI Flash now."

		run blink_work
		sleep 2
		run blink_work
		sleep 2
		run blink_work
		sleep 2
		run blink_work
		sleep 2
		run blink_work
		sleep 2

		if sf probe; then

		  # erase all mtd partitions containing u-boot
		  run blink_work
		  run blink_work
		  run blink_work
		  mtd erase u-boot-spl
		  run blink_work
		  run blink_work
		  run blink_work
		  mtd erase u-boot
		  run blink_work
		  run blink_work
		  run blink_work
		  mtd erase u-boot-env

		  led work on
		  echo "Erased U-Boot from SPI Flash."
		  while true; do sleep 1; done
		else
		  echo "Error: No SPI flash."
		  # blink both LEDs forever
		  while true; do run blink_diy; run blink_work; done
		fi
	EOF

	cat <<-'EOF' | tee "$R/tmp/kernels/u-boot-rockpro64/scripts/flash-spi.cmd" > /dev/null
		setenv blink_work 'led work on; sleep 0.1; led work off; sleep 0.1'
		setenv blink_diy 'led diy on; sleep 0.1; led diy off; sleep 0.1'

		run blink_work
		if sf probe; then
		  run blink_work

		  if size ${devtype} ${devnum}:${distro_bootpart} spi_combined.img; then
		    run blink_work
		    load ${devtype} ${devnum}:${distro_bootpart} ${kernel_addr_r} spi_combined.img
		  
		    # write flash
		    run blink_work
		    run blink_work
		    run blink_work
		    sf update ${kernel_addr_r} 0 ${filesize}
		    run blink_work
		    run blink_work
		    run blink_work
		  
		    led work on
		    echo "Wrote U-Boot to SPI Flash successfully."
		    while true; do sleep 1; done
		  else
		    echo "Error: Missing spi_combined.img"
		    # blink red LED forever
		    while true; do run blink_diy; sleep 0.1; done
		  fi
		else
		  echo "Error: No SPI flash."
		  # blink both LEDs forever
		  while true; do run blink_diy; run blink_work; done
		fi	
	EOF

	# The procedure if you have idbloader.img and u-boot.itb on an sdcard. 
	cat <<-'EOF' | tee  tee "$R/tmp/kernels/u-boot-rockpro64/scripts/load-spi-from-usb.cmd" > /dev/null
		if ls usb 0:1; then
			if sf probe; then
				load usb 0:1 ${fdt_addr_r} idbloader.img
				sf update ${fdt_addr_r} 0 ${filesize}
				load usb 0:1 ${fdt_addr_r} u-boot.itb
				sf update ${fdt_addr_r} 60000 ${filesize}
			else
				echo "Error: No SPI flash."
				# blink both LEDs forever
				while true; do run blink_diy; run blink_work; done
			fi
		else
			echo "Error: No USB available."
		fi	
	EOF
}

create-rockpro64-scripts(){
	cat <<-'EOF' | tee /usr/local/sbin/rockpro64_enable_eth_gadget.sh > /dev/null
		#!/bin/bash

		set -xe

		# enable peripheral mode
		enable_dtoverlay usb0_dwc3_peripheral usb0/dwc3@fe800000 okay \
		  'dr_mode="peripheral"'

		# reload dwc3
		echo fe800000.dwc3 > /sys/bus/platform/drivers/dwc3/unbind
		echo fe800000.dwc3 > /sys/bus/platform/drivers/dwc3/bind

		# install eth gadget
		install_gadget RockPro64 fe800000.dwc3 ecm
	EOF

	cat <<-'EOF' | tee /usr/local/sbin/rockpro64_disable_otg.sh > /dev/null
		#!/bin/bash

		set -x

		# enable peripheral mode
		disable_dtoverlay dwc3_peripheral

		# reload dwc3
		echo fe800000.dwc3 > /sys/bus/platform/drivers/dwc3/unbind
		echo fe800000.dwc3 > /sys/bus/platform/drivers/dwc3/bind

		# install eth gadget
		uninstall_gadgets
	EOF
	
	cat <<-'EOF' | tee /usr/local/sbin/rockpro64_reset_emmc.sh > /dev/null
		#!/bin/bash
		
		if [[ "$1" != "--force" ]]; then
		    MNT_DEV=$(findmnt / -n -o SOURCE)
		    if [[ "$MNT_DEV" == /dev/mmcblk1* ]]; then
			echo "Cannot reset when running from eMMC, use: $0 --force."
			exit 1
		    fi
		fi

		if [[ -d /sys/bus/platform/drivers/sdhci-arasan/fe330000.sdhci ]]; then
		    echo "Unbinding..."
		    echo fe330000.sdhci > /sys/bus/platform/drivers/sdhci-arasan/unbind
		fi

		echo "Binding..."
		echo fe330000.sdhci > /sys/bus/platform/drivers/sdhci-arasan/bind

		echo "Finished"
	EOF

	cat <<-'EOF' | tee /usr/local/sbin/rockpro64_reset_spi_flash.sh > /dev/null
		#!/bin/bash

		if [[ -d /sys/bus/platform/drivers/rockchip-spi/ff1d0000.spi ]]; then
		    echo "Unbinding..."
		    echo ff1d0000.spi > /sys/bus/platform/drivers/rockchip-spi/unbind
		fi

		echo "Binding..."
		echo ff1d0000.spi > /sys/bus/platform/drivers/rockchip-spi/bind

		echo "Finished"
	EOF
}

