#!/bin/sh

usage() {
	cat <<-__EOF__
		$PROGRAM $version
		usage: $PROGRAM [-fhUusv] SOURCE [DEST]
		       $PROGRAM -c DIR

		Copy the contents of SOURCE to DEST and make DEST bootable.

		SOURCE can be a directory or a ISO image. DEST can be a mounted directory
		or a device. If DEST is ommitted /media/usb will be used.

		Options:
		 -f  Force overwrite existing files. Will overwrite syslinux.cfg if upgrade.
		 -h  Show this help.
		 -k  fix kernel and initrd name in syslinux.cfg if needed.
		 -U  Replace current alpine_dev in syslinux.cfg with UUID if UUID found.
		 -u  Upgrade mode. Keep existing syslinux.cfg and don't run bootloader.
		 -s  Force run bootloader, even if upgrade mode.
		 -v  Verbose mode. Display whats going on.

		 -c  Check syslinux.cfg in destination DIR. Use with -f to fix.

		Environment:
		 BOOTLOADER=syslinux|none  Defaults to syslinux on x86, none elsewhere.

	__EOF__
	exit 1
}

while getopts "c:fhkUusv" opt; do
	case "$opt" in
	c) check_syslinux="$OPTARG";;
	f) force=1; fix_syslinux_cfg=1;;
	h) usage;;
	k) fix_syslinux_cfg=1;;
	U) replace_alpine_dev=1;;
	u) upgrade=1;;
	s) force_bootloader=1;;
	v) VERBOSE=1; export VERBOSE;;
	\?) usage;;
	*) usage;;
	esac
done

shift $((OPTIND - 1))

dev="$1"

[ -z "$dev" -o ! -b "$dev" ] && usage

case "$(uname -m)" in
	x86_64)
		bg_arch="x64"
		;;
	aarch64)
		bg_arch="a64"
		;;
	*)
		echo "Unsupported CPU architecture '$(uname -m)'!"
		exit 1
esac

# remove previous data
wipefs --all "$dev"
parted -s "$dev" mklabel gpt

disk_size=$(blockdev --getsize64 $dev)

echo "Partitioning disk"
sfdisk "$dev" <<__EOP__
label: gpt
device: $dev
unit: sectors

1: size=2048,type=21686148-6449-6E6F-744E-656564454649,name=bios_grub
2: size=128MiB,type=C12A7328-F81F-11D2-BA4B-00A0C93EC93B,name=efi
3: size=1792MiB,type=EBD0A0A2-B9E5-4433-87C0-68B6B72699C7,name=rkos-sys-1
4: size=1792MiB,type=EBD0A0A2-B9E5-4433-87C0-68B6B72699C7,name=rkos-sys-2
5: type=00000000-0000-0000-0000-000000000000
__EOP__

echo "Restart mdev service"
rc-service -q mdev restart

echo "Create file systems"
mount_dir=$(mktemp -d)
trap exiting "umount $mount_dir; rmdir $mount_dir"
for i in "efi:${dev}2" "rkos-sys-1:${dev}3" "rkos-sys-2:${dev}4"; do
	_label="${i%:*}"
	_part="${i#*:}"
	echo " $_part => $_label"
	mkfs.vfat -n "$_label" "$_part"
	mount "$_part" "$mount_dir"
	case "$_label" in
		efi)
			mkdir -p "$mount_dir/EFI/boot"
			cp /usr/lib/efibootguard/efibootguard$bg_arch.efi "$mount_dir/EFI/boot/boot$bg_arch.efi"
			;;
		rkos-sys-*)
			echo -n "$_label" | iconv -f ascii -t UTF-16LE > "$mount_dir/EFILABEL"
			bg_setenv -f "$mount_dir/BGENV.DAT" -r "${_label##*-}" --kernel="C:$_label:unified-lts" --args="modules=loop,squashfs,sd-mod,usb-storage quiet console=tty1 console=ttyS0,115200"
	esac
	umount "$_part"
done
