#!/bin/bash

#
# Update the BOOTX64.EFI application with the GoboLinux partition's UUID.
# The script assumes that GoboLinux is installed on the same disk as the
# EFI partition.
#
# Written by Lucas C. Villa Real <lucasvr@gobolinux.org>
#
# Released under the GNU GPL version 2 or above.
#

gobodisk=
testdir=$(dirname $(readlink -f "$0"))
while true
do
  if mountpoint -q "$testdir"
  then
    gobodisk=$(mount | grep "on ${testdir} type" | awk {'print $1'} | sed 's,[0-9]*,,g')
    gobodisk=$(basename ${gobodisk})
    break
  elif [ "$testdir" = "/" ]
  then
    echo "Could not detect GoboLinux installation disk"
    exit 1
  fi
  testdir=$(readlink -f "$testdir/..")
done

gobopart=
mkdir -p /tmp/testgobo
for partnum in /dev/${gobodisk}*
do
  if mount $partnum /tmp/testgobo
  then
    if [ -d /tmp/testgobo/Programs ]
    then
      gobopart=$partnum
      umount /tmp/testgobo
      break
    fi
    umount /tmp/testgobo
  fi
done
rmdir /tmp/testgobo

if [ -z "$gobopart" ]
then
  echo "Could not detect GoboLinux installation partition"
 # exit 1
fi

echo "GoboLinux is installed on $gobopart"
#old_part_uuid=$(cat grub-efi.cfg | grep "search --no-floppy" | awk {'print $NF'} | head -n1)
#new_part_uuid=$(blkid -s UUID -o value ${gobopart})
#sed -i "s/$old_part_uuid/$new_part_uuid/g" grub-efi.cfg

grub-mkstandalone-efi -d /Programs/GRUB-EFI/Current/lib/grub/x86_64-efi -O x86_64-efi --modules="part_gpt part_msdos iso9660 all_video efi_gop efi_uga video_bochs video_cirrus gfxterm gettext font" --fonts="unicode" --themes="" -o BOOTX64.EFI --compress=gz "boot/grub/grub.cfg=grub-efi.cfg"

#efibootmgr --create --label "GoboLinux" --loader /Mount/EFI/EFI/BOOT/BOOTX64.EFI --disk /dev/sdb --part 1
