#!/usr/bin/env sh

# Read /etc/hwrevision and turn it into a stripped string
# with the format ${MACHINE}_${VERSION}
HWREVISION=$(tr ' ' '_' < /etc/hwrevision | tr -d '[:space:]')

# Format the disk
SFDISK_DUMP_FILE="/etc/${HWREVISION}.sfdisk"

if [ ! -f "${SFDISK_DUMP_FILE}" ]
then
    echo "Configuration file ${SFDISK_DUMP_FILE} not found"
    exit 1
fi

DISK=$(grep "^device:\s" < "${SFDISK_DUMP_FILE}" | cut -d ' ' -f 2)

echo "Flashing ${SFDISK_DUMP_FILE} to ${DISK}"
cat "${SFDISK_DUMP_FILE}"
sfdisk "${DISK}" < "${SFDISK_DUMP_FILE}"

# Give the kernel some time to reload the partition
sleep 3

# Create EFI and EFIBootGuard partition as FAT16
mkfs.fat -F 16 -n EFI /dev/disk/by-partlabel/efi
mkfs.fat -F 16 -n EBG0 /dev/disk/by-partlabel/ebg0
mkfs.fat -F 16 -n EBG1 /dev/disk/by-partlabel/ebg1

mkdir -p /mnt/ebg0
mkdir -p /mnt/ebg1
mkdir -p /mnt/efi

mount /dev/disk/by-partlabel/ebg0 /mnt/ebg0
mount /dev/disk/by-partlabel/ebg1 /mnt/ebg1
mount /dev/disk/by-partlabel/efi /mnt/efi

mkdir -p /mnt/efi/EFI/BOOT

echo -n "EBG0" | iconv -f ascii -t UTF-16LE > /mnt/ebg0/EFILABEL
bg_setenv -f /mnt/ebg0/BGENV.DAT -r 0 -s FAILED

echo -n "EBG1" | iconv -f ascii -t UTF-16LE > /mnt/ebg1/EFILABEL
bg_setenv -f /mnt/ebg1/BGENV.DAT -r 0 -s FAILED

umount /mnt/ebg0
umount /mnt/ebg1
umount /mnt/efi

SWUPDATE_ARGS="${SWUPDATE_ARGS} -e stable,copy0"
