#!/bin/sh
set -e

DEV="$1"
if [ -z "$DEV" ] || ! shift || [ -n "$*" ]; then
    echo >&2 "Usage: $0 /dev/your-sd-or-mmc-or-image"
    exit 1
fi

if [ ! -w "$DEV" ]; then
    echo >&2 "$0: device/image ($DEV) must be writable"
    exit 1
fi
DEV="$(readlink -f "$DEV")"
DIR="$(mktemp -d)"
trap 'rm -rf "$DIR"' 0
# Build tools get confused by paths, thus let's copy all the pieces into
# one dir.

if [ ! -w "$DEV" ]; then
    echo >&2 "$0: device/image ($DEV) not accessible via abs path?!?"
    exit 1
fi

cd "$DIR"
# A very simple sanity check.  GPT mandates a "protective MBR" so this works
# even with GPT partitioning.
printf '%b' '\0125\0252' >mbr-sign
if ! cmp -s -i 0:510 -n 2 mbr-sign "$DEV"; then
   echo >&2 "$0: device/image ($DEV) has no MBR partition table"
   exit 1
fi

cp -p /usr/lib/u-boot/pine64_plus/*.dtb /usr/lib/u-boot/pine64_plus/*.bin .
BL31=/usr/lib/atf/sun50iw1p1/bl31.bin \
    sh /usr/share/doc/u-boot-sunxi/mksunxi_fit_atf.sh *.dtb > u-boot.its
mkimage -f u-boot.its u-boot.itb
echo "Writing sunxi-spl"
dd conv=notrunc if=sunxi-spl.bin of="$DEV" bs=8k seek=1
echo "Writing u-boot FIT image"
dd conv=notrunc if=u-boot.itb of="$DEV" bs=8k seek=5
sync "$DEV"
