#!/bin/sh
set -e

# GRUB2 Helper Script - Pisi Linux / Custom ISO
prefix="/usr"
exec_prefix="/usr"
datarootdir="/usr/share"

export TEXTDOMAIN=grub
export TEXTDOMAINDIR="${datarootdir}/locale"

. "${datarootdir}/grub/grub-mkconfig_lib"

# 1. EFI Firmware (BIOS Setup) Menü Eklentisi
efi_vars_dir=/sys/firmware/efi/efivars
EFI_GLOBAL_VARIABLE=8be4df61-93ca-11d2-aa0d-00e098032b8c
OsIndications="$efi_vars_dir/OsIndicationsSupported-$EFI_GLOBAL_VARIABLE"

if [ -e "$OsIndications" ] && \
   [ "$(( $(printf 0x%x \'"$(cat $OsIndications | cut -b1)") & 1 ))" = 1 ]; then
  LABEL="System setup"

  cat << EOF
if [ "\$grub_platform" = "efi" ]; then
	fwsetup --is-supported
	if [ "\$?" = 0 ]; then
		menuentry '$LABEL' \$menuentry_id_option 'uefi-firmware' {
			fwsetup
		}
	fi
fi
EOF
fi

if [ -d /sys/firmware/efi ]; then

  TEMP_MOUNT="/tmp/grub_win_detect"
  WIN_UUID=""

  EFI_PARTS=$(lsblk -list -no NAME,FSTYPE 2>/dev/null | awk '$2=="vfat" {print $1}')

  for part in $EFI_PARTS; do
      DEV="/dev/$part"

      MNT=$(findmnt -n -o TARGET "$DEV" 2>/dev/null || true)
      WAS_MOUNTED=1

      if [ -z "$MNT" ]; then
          WAS_MOUNTED=0
          MNT="$TEMP_MOUNT"
          mkdir -p "$MNT"
          mount -o ro "$DEV" "$MNT" 2>/dev/null || continue
      fi

      if [ -f "$MNT/EFI/Microsoft/Boot/bootmgfw.efi" ]; then
          WIN_UUID=$(blkid -s UUID -o value "$DEV" 2>/dev/null || true)
          if [ "$WAS_MOUNTED" -eq 0 ]; then
              umount "$MNT" 2>/dev/null || true
          fi
          break
      fi

      if [ "$WAS_MOUNTED" -eq 0 ]; then
          umount "$MNT" 2>/dev/null || true
      fi
  done

  rm -rf "$TEMP_MOUNT"

  if [ -n "$WIN_UUID" ]; then
cat << EOF
menuentry "Windows Boot Manager (UEFI)" --class windows --class os {
  insmod part_gpt
  insmod fat
  insmod search_fs_uuid
  insmod chain
  search --fs-uuid --set=root ${WIN_UUID}
  chainloader /EFI/Microsoft/Boot/bootmgfw.efi
}
EOF
  fi

fi
