#!/bin/bash

# /root/partition-efi
# Create default partition scheme for EFI-based Hardware Models.
# This is used for the Slackware ARM build systems.
# mozes@slackware.com

# Determine the Hardware Model name:
export HWM=$( slk-hwm-discover )

# Set boot parameters for supported Hardware Models:
# This may be split into helper scripts (a la Kernel Module Loader)
# if the number of boards exceeds several.
case $HWM in
   "SolidRun CEX7 Platform"*|"SolidRun LX2160A Honeycomb"*|"Parallels"*)
   DISK=/dev/sda ;;

   "KVM Virtual"*|"QEMU Virtual"*|"Apple Virtual"*)
   DISK=/dev/vda ;;

   "VMware Apple"*)
   DISK=/dev/nvme0n1 ;;

   *) unset DISK;;
esac

[ -z "${DISK}" ] && { echo "Unable to determine the storage block device for Hardware Model: ${HWM}" ; exit 1; }

echo "Hardware Model: ${HWM}"
echo "Storage.......: ${DISK}"

read -p "Press ENTER to partition your storage. This will DESTROY your data"

# Wipe first 10MB (enough to erase MBR/GPT + boot signatures):
dd if=/dev/zero of="$DISK" bs=1M count=10 conv=fsync

# Wipe the last 10MB (to remove GPT backup headers):
DISK_SIZE=$( blockdev --getsz "$DISK" )
SECTOR_SIZE=$( cat /sys/block/$(basename "$DISK")/queue/hw_sector_size )
END_SECTOR=$((DISK_SIZE - 20480))  # 10MB worth of sectors
dd if=/dev/zero of="$DISK" bs=$SECTOR_SIZE seek=$END_SECTOR count=20480 conv=fsync

echo "Creating GPT partition table on $DISK..."
parted --script "$DISK" mklabel gpt

echo "Creating 100MB EFI System Partition..."
parted --script "$DISK" mkpart ESP fat32 1MiB 101MiB
parted --script "$DISK" set 1 esp on
parted --script "$DISK" set 1 boot on

echo "Creating 6GB Linux Swap Partition..."
parted --script "$DISK" mkpart primary linux-swap 101MiB 6245MiB

echo "Creating Linux Filesystem Partition (rest of disk)..."
parted --script "$DISK" mkpart primary ext4 6245MiB 100%

echo "Formatting EFI Partition as FAT32..."
mkfs.fat -F32 "${DISK}1"

echo "Setting up swap on partition 2..."
mkswap "${DISK}2"

echo "Formatting root filesystem on partition 3 as ext4..."
mkfs.ext4 "${DISK}3" -O 64bit

echo "Done. Partition table on $DISK:"
parted "$DISK" print

