#!/bin/bash
# Tool to create a GPT partition table for LVM PV with both EFI, and BIOS boot partitions
# Loosely based on https://blog.heckel.io/2017/05/28/creating-a-bios-gpt-and-uefi-gpt-grub-bootable-linux-system
#
# Proper checks on whether or not sdX is in use seems almost impossible, but sgdisk should fail
# As a starting point: /proc/mounts, /proc/swaps, /proc/mdstat
# A drive can be part of an active LVM pv (use pvdisplay)
# A drive can be directly accessed by an application (e.g. Oracle supports writing directly to a drive or partition instead of a filesystem) (use fuser)
# A drive can be directly accessed by a virtual machine (use fuser)
# A drive can be referenced by a loopback device (e.g: mount /dev/sda -o offset=1M /foo) (use losetup -a)
# There is a ton of other cases too

if [ $# -lt 2 ]; then
	echo "Usage: part_gpt_boot.sh [/dev/sdX] [SURE]"
	echo "Make sure /dev/sdX isn't in use, I won't try too hard checking it!"
    exit 3
fi

DISK=$1
DISKEND=${DISK##*/}

if ! [[ "`lsblk -nd| awk '{print $1}'`" == *"$DISKEND"* ]]; then echo "No such disk as $DISK"; exit 2; fi

# 2DO it makes a few false positives such as sds is a substring of ssdstore
if [[ "`pvs | awk '{print $1}' | cat /proc/mdstat /proc/swaps /proc/mounts  -`" == *"$DISKEND"* ]]; then echo "$DISK is in use!"; exit 3; fi

if [ "$2" != "SURE" ]; then
	exit 1
fi

if ! [ -d "$ROOTDIR/etc" ]; then
    echo "Root dir $ROOTDIR doesn't exist"
    exit 23
fi

# sgdisk -L # list all typecodes
sgdisk --clear \
  --new 1::+1M --typecode=1:ef02 --change-name=1:'BIOS boot partition' \
  --new 2::+100M --typecode=2:ef00 --change-name=2:'EFI System' \
  --new 3::-0 --typecode=3:fd00 --change-name=3:'Linux md raid' \
  $DISK
#  test.img

echo "run the following"
echo "mkfs.fat -F32 ${DISK}2"
echo "${DISK}3 can be used as md disk"
