#!/bin/sh
# Zedboard

set -e

mk_sudo=sudo

img_size=512
img_image="$(pwd)/imgs/sdcard.img"
img_devid="0"
img_dev="md${img_devid}"
img_devsize="count=1048576"
img_mnt="$(pwd)/mnt"
img_uboot="$(pwd)/u-boot/u-boot.img"
img_bootbin="$(pwd)/u-boot/spi/boot.bin"
img_uenv="$(pwd)/config/uEnv.txt"
img_dtb="$(pwd)/u-boot/board.dtb"

# Source in config/mk.conf if it exists.
if [ -r config/mk.conf ] ; then
    . config/mk.conf
fi

dev_active="NO"
boot_mounted="NO"

# Clean up
cleanup()
{
 if [ ${boot_mounted} = "YES" ]; then
  ${mk_sudo} umount ${img_mnt}/boot
 fi
 if [ ${dev_active} = "YES" ]; then
  ${mk_sudo} mdconfig -d -u ${img_devid}
 fi
 ${mk_sudo} rm -rf umount ${img_mnt}/boot
 ${mk_sudo} rm -rf umount ${img_mnt}/root
}

# clean up on exit
trap cleanup EXIT

# Make an image
dd if=/dev/zero of=${img_image} ${img_devsize}
${mk_sudo} mdconfig -f ${img_image} -u ${img_devid}
dev_active="YES"

# Create the boot partition, a Zynq need a DOSFS root.
# Note, the boot.bin file must be a SFN or an 8.3 format. It cannot
#       be 8.3 in a LFN directory entry.
${mk_sudo} gpart create -s MBR ${img_dev}
${mk_sudo} gpart add -s64m -t \!14 ${img_dev}
${mk_sudo} gpart set -a active -i 1 ${img_dev}
${mk_sudo} newfs_msdos -F 16 /dev/${img_dev}s1

mkdir ${img_mnt}/boot

# Load the boot partition files
${mk_sudo} mount -t msdosfs /dev/${img_dev}s1 ${img_mnt}/boot
boot_mounted="YES"
${mk_sudo} cp ${img_uboot} ${img_mnt}/boot/u-boot.img
${mk_sudo} cp ${img_bootbin} ${img_mnt}/boot/boot.bin
${mk_sudo} cp ${img_uenv} ${img_mnt}/boot/uEnv.txt
${mk_sudo} cp ${img_dtb} ${img_mnt}/boot/system.dtb

