#!/bin/bash

set -e

m1n1=/usr/lib/m1n1
uboot=/usr/lib/u-boot-asahi

for i in /boot/efi/m1n1 /boot/m1n1; do
	if [ -d "$i" ]; then
		m1n1_dir="$i"
		break
	fi
done

if [ -z "$m1n1_dir" ]; then
	echo "$m1n1_dir does not exist, is /boot/efi mounted?" 1>&2
	exit 1
fi

target="${2:-$m1n1_dir/boot.bin}"
echo $target

if [ ! -z $1 ]
then
	DTBS=$1/apple/*
else
	DTBS=/boot/dtbs-asahi/apple/*
fi

cat "$m1n1/m1n1.bin" $DTBS \
    <(gzip -c "$uboot/u-boot-nodtb.bin") \
    >"${target}.new"
mv ${target} ${target}-`date +%Y%m%d%H%M`
mv -f "${target}.new" "$target"

echo "m1n1 updated at ${target}"
