#!/bin/bash

# omarchy:summary=Print the EFI system partition systemd-boot starts from and the partition its boot images go on
# omarchy:args=[--fstab FILE] [--devices] [--expect ESP BOOT]
# omarchy:hidden=true

# One line: the ESP systemd-boot starts from, a tab, and $BOOT, where the boot
# images go; with --devices, then each one's device. Beside Windows' ESP at
# /efi, too small for them, an XBOOTLDR partition at /boot on the same disk
# holds them; otherwise both are one ESP, at /efi where an install put it there
# and /boot everywhere else.
#
# Both roles come from fstab and the live mounts together, which must agree.
# What can't be told for certain (an autofs or unmounted volume, a /boot whose
# type can't be read, an XBOOTLDR on another disk) is refused on stderr with
# exit 1, so no writer guesses. Both volumes must be mounted, unless --fstab
# reads another root's fstab alone, as a factory reset does. --expect checks
# that the layout is the one a caller names, as the installer and a factory
# reset name it to the boot tooling, before anything is written.

set -euo pipefail

ESP_TYPE=c12a7328-f81f-11d2-ba4b-00a0c93ec93b
XBOOTLDR_TYPE=bc13c2ff-59e6-4262-a352-b275fd6f7172
DISK_BY=${OMARCHY_BOOT_DISK_BY:-/dev/disk}

fstab=${OMARCHY_BOOT_FSTAB:-/etc/fstab} live=1 devices=0 expect=""
while (($#)); do
  case $1 in
  --fstab) fstab=${2:?--fstab needs a file}; live=0; shift ;;
  --devices) devices=1 ;;
  --expect) expect="${2:?--expect needs ESP and BOOT} ${3:?--expect needs ESP and BOOT}"; shift 2 ;;
  *) echo "usage: omarchy-boot-partitions [--fstab FILE] [--devices] [--expect ESP BOOT]" >&2; exit 2 ;;
  esac
  shift
done

refuse() {
  echo "omarchy-boot-partitions: $*" >&2
  exit 1
}

# The device an fstab source names, or nothing when it isn't there, or when a
# FAT serial number names more than one partition.
spec_device() {
  local link
  if [[ $1 == UUID=* ]] && (($(lsblk -nro UUID 2>/dev/null | grep -cxF "${1#UUID=}" || true) > 1)); then
    return 0
  fi
  case $1 in
  UUID=*) link=$DISK_BY/by-uuid/${1#UUID=} ;;
  PARTUUID=*) link=${1#PARTUUID=}; link=$DISK_BY/by-partuuid/${link,,} ;;
  LABEL=*) link=$DISK_BY/by-label/${1#LABEL=} ;;
  PARTLABEL=*) link=$DISK_BY/by-partlabel/${1#PARTLABEL=} ;;
  /*) link=$1 ;;
  *) return 0 ;;
  esac
  [[ ! -e $link ]] || readlink -f "$link"
}

# Sets <role>_type, <role>_dev and <role>_mounted for the mountpoint $2 from
# fstab and, unless reading another root's fstab, the live mount there,
# refusing where the two disagree.
resolve() {
  local role=$1 mountpoint=$2 ftype="" fspec="" fdev="" ltype="" lsource="" ldev=""
  read -r ftype fspec < <(awk -v m="$mountpoint" '$1 !~ /^#/ && $2 == m { print $3, $1; exit }' "$fstab" 2>/dev/null) || true
  [[ -z $fspec ]] || fdev=$(spec_device "$fspec")
  if [[ $ftype == "vfat" && -z $fdev ]]; then
    refuse "fstab's $fspec for $mountpoint names no one partition that can be found"
  fi
  if ((live)); then
    # A path through an automount mounts it; one that stays autofs isn't
    # mounted, and one whose device never comes isn't waited on for long.
    timeout 10 ls -d "$mountpoint/." >/dev/null 2>&1 || true
    read -r ltype lsource < <(findmnt -n -o FSTYPE,SOURCE --mountpoint "$mountpoint" 2>/dev/null | tail -n 1) || true
    [[ $ltype != "autofs" ]] || ltype=""
    [[ -z $ltype || -z $lsource ]] || ldev=$(readlink -f "${lsource%%\[*}")
  fi
  if [[ -n $ftype && -n $ltype && $ftype != "$ltype" ]]; then
    refuse "$mountpoint is mounted as $ltype, but fstab says $ftype"
  fi
  if [[ $ftype == "vfat" && -n $ltype && -n $fdev && $fdev != "$ldev" ]]; then
    refuse "$mountpoint is mounted from $ldev, but fstab names $fdev"
  fi
  [[ $ftype != "vfat" ]] || printf -v "${role}_configured" 1
  if [[ $ftype == "vfat" || $ltype == "vfat" ]]; then
    printf -v "${role}_type" vfat
    printf -v "${role}_dev" '%s' "${ldev:-$fdev}"
    if [[ $ltype == "vfat" ]]; then printf -v "${role}_mounted" 1; fi
  fi
}

efi_type="" efi_dev="" efi_mounted=0 efi_configured=0 boot_type="" boot_dev="" boot_mounted=0 boot_configured=0 xbootldrs=0
resolve efi /efi
resolve boot /boot

# Sets xbootldrs to how many XBOOTLDR partitions are on the disk partition $1
# is on. A disk that can't be told or listed is refused, never counted as none.
count_xbootldrs() {
  local disk listing
  disk=$(lsblk -dno PKNAME "$1" 2>/dev/null) || disk=""
  [[ -n $disk ]] || refuse "which disk $1 is on can't be told"
  listing=$(lsblk -nro PARTTYPE "/dev/$disk" 2>/dev/null) || refuse "the partitions on /dev/$disk can't be listed"
  xbootldrs=$(grep -cxF "$XBOOTLDR_TYPE" <<<"$listing" || true)
}

if [[ -z $efi_type && -z $boot_type ]]; then
  refuse "no vfat EFI system partition at /efi or /boot"
elif [[ -z $efi_type ]]; then
  # A lone XBOOTLDR partition isn't an ESP, whatever fstab forgot.
  [[ $(lsblk -dno PARTTYPE "$boot_dev" 2>/dev/null) != "$XBOOTLDR_TYPE" ]] ||
    refuse "/boot ($boot_dev) is an XBOOTLDR partition, but no ESP is at /efi"
  esp=/boot boot=/boot
elif [[ -z $boot_type ]]; then
  # An XBOOTLDR partition on the ESP's disk is a split layout missing its
  # /boot (a snapshot's fstab without the row), not one ESP.
  count_xbootldrs "$efi_dev"
  ((xbootldrs == 0)) || refuse "an XBOOTLDR partition is on the ESP's disk, but nothing names it at /boot"
  esp=/efi boot=/efi
else
  [[ -n $efi_dev && -n $boot_dev ]] || refuse "/efi and /boot are both vfat, but which partitions they are can't be told"
  if [[ $efi_dev == "$boot_dev" ]]; then
    # A bind of the ESP at /boot is an alias only while fstab names one of
    # them; two rows naming one partition are a layout gone wrong.
    ((!(efi_configured && boot_configured))) ||
      refuse "fstab mounts the same partition ($efi_dev) at both /efi and /boot"
    count_xbootldrs "$efi_dev"
    ((xbootldrs == 0)) || refuse "/boot is the ESP at /efi again, though an XBOOTLDR partition is on its disk"
    esp=/efi boot=/efi
  else
    efi_parttype=$(lsblk -dno PARTTYPE "$efi_dev" 2>/dev/null || true)
    [[ $efi_parttype == "$ESP_TYPE" ]] ||
      refuse "/efi ($efi_dev) isn't an EFI system partition (type ${efi_parttype:-unreadable})"
    parttype=$(lsblk -dno PARTTYPE "$boot_dev" 2>/dev/null || true)
    [[ $parttype == "$XBOOTLDR_TYPE" ]] ||
      refuse "/boot ($boot_dev) is vfat beside the ESP at /efi but isn't an XBOOTLDR partition (type ${parttype:-unreadable})"
    efi_disk=$(lsblk -dno PKNAME "$efi_dev" 2>/dev/null || true)
    boot_disk=$(lsblk -dno PKNAME "$boot_dev" 2>/dev/null || true)
    [[ -n $efi_disk && $efi_disk == "$boot_disk" ]] ||
      refuse "the XBOOTLDR partition $boot_dev isn't on the same disk as the ESP $efi_dev, so systemd-boot wouldn't read it"
    count_xbootldrs "$efi_dev"
    ((xbootldrs == 1)) || refuse "the ESP's disk has more than one XBOOTLDR partition, and systemd-boot reads only one"
    esp=/efi boot=/boot
  fi
fi

role_dev() { if [[ $1 == /efi ]]; then echo "$efi_dev"; else echo "$boot_dev"; fi; }
if ((live)); then
  for mountpoint in "$esp" "$boot"; do
    if [[ $mountpoint == /efi ]]; then mounted=$efi_mounted; else mounted=$boot_mounted; fi
    ((mounted)) || refuse "$mountpoint isn't mounted"
  done
fi

if [[ -n $expect && $expect != "$esp $boot" ]]; then
  refuse "the boot tooling was told ESP and boot images at ${expect/ / and }, but fstab and the mounts say $esp and $boot"
fi

if ((devices)); then
  esp_dev=$(role_dev "$esp") images_dev=$(role_dev "$boot")
  [[ -n $esp_dev && -n $images_dev ]] || refuse "the device of $esp or $boot can't be found"
  printf '%s\t%s\t%s\t%s\n' "$esp" "$boot" "$esp_dev" "$images_dev"
else
  printf '%s\t%s\n' "$esp" "$boot"
fi
