#!/bin/sh

verbose=
board=oragepi-zero3
device=/dev/mmcblk0
dryrun=
imagedir=/usr/share/u-boot


die() {
	echo "ERROR: $@"
	exit 1
}

usage() {
	get_defaults

	cat <<EOF
usage: $0 [-n,--dry-run] [-i,--imagedir <imagedir>] [-b|--board <board-type>] [-d|--device <device>]

options:

 -b,--board <board>       Specify the board type: orangepi-zero3 
                          (current default: ${board:-none})

 -d,--device <device>     Specify the device where to install u-boot
                          (current default: ${device:-none})

 -i,--imagedir <imagedir> Specify u-boot image directory
                          (current default: ${imagedir:-none})

 -n,--dry-run             Print commands but don't execute them

EOF
}

while [ $# -gt 0 ]; do
	opt="$1"
	shift
	case "$opt" in
	-b|--board)
		case "$1" in
		orangepi-zero3) board="orangepi-zero3" ;;
		*) usage; exit 1;;
		esac
		shift
		;;
	-d|--device)
		device="$1"
		shift
		;;
	-i|--imagedir)
		imagedir="$1"
		shift
		;;
	-n|--dry-run)
		dryrun="echo"
		;;
        --)
                break
                ;;
        -*)
                usage
                exit 1
                ;;
        esac
done

if [ -z "$board" -o -z "$device" -o -z "$imagedir" -o  ! -e "$imagedir" ]; then
	usage
	exit 1
fi

if [ -z "$dryrun" ]; then
	echo "Updating $board u-boot in $device in 3 seconds..."
	sleep 3
fi

(
set -e
case "$board" in
orangepi-zero3)
	[ -e "$imagedir/orangepi_zero3" ] || die "orangepi-zero3 images not installed, apk add u-boot-xunlong-orangepi-zero3"
	$dryrun dd if=$imagedir/orangepi_zero3/u-boot-sunxi-with-spl.bin of=$device bs=1024 seek=8 status=none
	;;
esac
$dryrun sync
) || die "U-Boot installation in $device failed"

[ -z "$dryrun" ] && echo "Completed successfully."
