#!/bin/bash
set -eu

UKI_ROOT='/boot/efi/EFI/puavo'

panic() {
  echo "error: $1" >&2
  exit 1
}

usage() {
  echo "Usage: $0 <images-dir>" >&2
  exit 1
}

find_efi_device_path() {
  local diskdev="$1"

  lsblk -n -l -o PATH,PARTTYPE "$diskdev" \
    | awk '$2 == "c12a7328-f81f-11d2-ba4b-00a0c93ec93b" { print $1; exit(0) }'
}

cleanup() {
  umount /boot/efi 2>/dev/null || true
}

trap cleanup EXIT

[ $# -eq 1 ] || usage
images_dir=$1

mountpoint -q "$images_dir" || panic "images directory '${images_dir}' is not mounted"

boot_disks=$(/usr/lib/puavo-core/puavo-get-boot-disks "$images_dir")
[ -n "$boot_disks" ] || panic "failed to find boot disks"

is_uki_install=''

for diskdev in $boot_disks; do
  # Check if the disk contains UKI installation
  is_uki_disk=0

  # Find and mount the EFI partition of the current disk device.
  # UKI installation requires the existence of EFI partition.
  efi_device_path=$(find_efi_device_path "$diskdev")

  if [ -n "$efi_device_path" ]; then
    if ! mount "$efi_device_path" /boot/efi >/dev/null 2>&1; then
      panic "failed to mount EFI partition of device ${diskdev}"
    fi

    if [ -d "$UKI_ROOT" ]; then
      is_uki_disk=1
    fi

    umount /boot/efi || true
  fi

  # Update the result and ensure it stays consistent
  if [ -z "$is_uki_install" ]; then
    is_uki_install="$is_uki_disk"
  elif [ "$is_uki_install" != "$is_uki_disk" ]; then
    panic "inconsistent UKI installation state detected on $diskdev"
  fi
done

echo "$is_uki_install"
