#!/bin/bash

# This script creates a u-boot bootscript file from a template. It runs during
# postinst, when triggered by changes to the host's boot directory, and by
# mkos-mlo-common during image construction.
#
# Environment variables: DEV, UNAME, INFILE, OUTFILE
#
# Examples:
#   $ /boot/update-bootscr
#
#   $ DEV=mmcblk1p1 /emmc/boot/update-bootscr
#
#   $ chroot emmc
#   $ /boot/update-bootscr
#

INFILE="${INFILE:-/boot/boot.txt.in}"
OUTFILE="${OUTFILE:-/boot/boot.scr}"

# Use findmnt(8) to find our root device, unless we've already been told.
#
# Using findmnt identifies host device correctly if we're chrooted, which is
# what we want when, i.e., debootstrap is trying to run a native, second-stage
# operation:
#
#  $ findmnt -n /
#    /      /dev/mmcblk1p1 ext4   rw,relatime
#
#  $ chroot <emmc>
#  $ findmnt -n /
#    /      /dev/mmcblk0p1 ext4   rw,relatime
#
DEV="${DEV:-$(findmnt -n /)}"
oldDEV="$DEV"

# Make sure the answer is something we recognize: if it doesn't refer to a
# partition on an mmcblk device, it's unlikely we're in the right building.
DEV="$(echo $DEV | grep -o -e "mmcblk[[:digit:]]p[[:digit:]]")"

# Parse the device and partition fields.
BOOTDEV="$(echo ${DEV} | cut -b 7)"
BOOTPART="$(echo ${DEV} | cut -b 9)"

# Did we end up with anything?
if [[ -z "$DEV" || -z "$BOOTDEV" || -z "$BOOTPART" ]] ; then
    echo "DEV must be mmcblk[:digit:]p[:digit:] (DEV=$oldDEV)"
    exit 1 # Nope.
fi

# Guess our kernel name from the list of options in BASE_DIR, unless we've been told the answer already.
UNAME="${UNAME:-$(find /boot -name "vmlinuz-*" -type f | sort -n | tail -n 1 | sed "s%/boot/vmlinuz-%%g")}"
if [[ -z "$UNAME" ]] ; then
    echo "Can't find a UNAME in /boot"
    exit 1
fi

# Fill out the various fields in $INFILE to create a temporary input file for
# mkimage.  We have to do this in a tempfile, since mkimage won't take input
# from stdin.
TMPFILE=$(mktemp)
trap "rm -f $TMPFILE" EXIT
sed "s/\${BOOTDEV}/${BOOTDEV}/g;s/\${BOOTPART}/${BOOTPART}/g;s/\${UNAME}/${UNAME}/g" < $INFILE > $TMPFILE

# Print some helpful diagnostics.
grep "setenv" $TMPFILE | grep -e uname -e bootpart

# Finally, write the bootscript.
mkimage -A arm -O linux -T script -C none -n "bootscript" -d $TMPFILE $OUTFILE
