#!/bin/dash -eu

verbose() {
	local progname="${0##*/}"
	echo "$progname: $*" >&2
}

fatal() {
	verbose "$*"
	exit 1
}

read_gpt() {
	local offset=$((sector_size + $1))
	dd if="$dev" bs=1 skip=$offset count=4 2>/dev/null | hexdump '-e"%u"'
}

read_entry() {
	local offset=$((sector_size * 2 + $1))
	local x="$(dd if="$dev" bs=1 skip=$offset count=1 2>/dev/null)"
	printf "%u" "'$x"
}


boot_dir="${1:-/boot}"
boot_majmin="$(mountpoint -d "$boot_dir")" ||:
sysfs_path="$(readlink -fv "/sys/dev/block/$boot_majmin" 2>/dev/null)" ||
	fatal "Unable to get sysfs path"

[ -f "$sysfs_path/partition" ] ||
	fatal "Boot device must be partition"

read partition < "$sysfs_path/partition"
dev="$(sed -n -e 's,^DEVNAME=,/dev/,p' "${sysfs_path%/*}/uevent")"
sector_size=$(blockdev --getss "$dev")

verbose "Device name: $dev"
verbose "Sector size: $sector_size"

magic="$(dd if="$dev" bs=2 skip=255 count=1 2>/dev/null | base64)"
[ "$magic" = "Vao=" ] ||
	fatal "Unknown partition table"

magic="$(dd if="$dev" bs=8 skip=64 count=1 2>/dev/null)"
if [ "$magic" = "EFI PART" ]; then
	partition_table='gpt'
	magic=$(read_gpt 80)
else
	partition_table='msdos'
	magic=4
fi

verbose "Partition table: $partition_table"

[ $partition -ge 1 -a $partition -le $magic ] ||
	fatal "invalid partition number: $partition"

if [ "$partition_table" = "msdos" ]; then
	magic=$((16 * $((partition - 1)) + 446))
	magic="$(dd if="$dev" bs=1 skip=$magic count=1 2>/dev/null | base64)"
	[ "$magic" = "gA==" ] ||
		fatal "partition not bootable"
	mbr_bin='mbr.bin'
else
	magic=$(read_gpt 84)
	magic=$((magic * $((partition - 1)) + 48))
	magic=$(read_entry $magic)
	magic=$((magic & 4))
	[ "$magic" = "4" ] ||
		fatal "partition not bootable"
	mbr_bin='gptmbr.bin'
fi

verbose "Boot code: $mbr_bin"

exit 0
