#!/bin/sh

# Assuming we've booted to SD, we write a new filesystem to eMMC.
#
# NOTE: DO NOT ATTEMPT TO RUN THIS SCRIPT FROM EMMC!
#
# Requires a copy of the pre-unpacked filesystem, i.e.:
#    $ fakeroot mkos-deadbolt -z

BOOTDEV=1
BOOTPART=1
FS=ptux.tgz

EMMCDEV=/dev/mmcblk${BOOTDEV}p${BOOTPART}

if [ ! -f ${FS} ] ; then
    Missing filesystem image copy: ${FS}
    exit 1
fi

if [ ! -b ${EMMCDEV} ] ; then
    Cannot find block device: ${EMMCDEV}
    exit 1
fi

mkfs.ext4 ${EMMCDEV}

TMPDIR=$(mktemp -d)
trap "umount $TMPDIR; rm -rf $TMPDIR" EXIT

mount ${EMMCDEV} $TMPDIR

echo Installing filesystem...
cat ${FS} | pv -s $(du -sb ${FS}) | tar xz -C ${TMPDIR}

# Set up boot.scr with the right root=PARTUUID=<uuid> source.
echo Adjusting boot script...
(cd ${TMPDIR}/boot && mkimage -A arm -O linux -T script -C none -n "bootscript" -d boot-emmc.txt boot.scr)

# Make sure there isn't a copy of us in the eMMC filesystem: running us over
# there would likely trash the system, because this script is so dumb...
rm -f ${TMPDIR}/root/$0
