#! /bin/sh

# Install GRUB on your EFI partition.
# Copyright (C) 1999,2000,2001,2002,2003,2004,2005,2006,2007,2008  Free Software Foundation, Inc.
#
# GRUB is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GRUB is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GRUB.  If not, see <http://www.gnu.org/licenses/>.

# Initialize some variables.
transform="s&^&&"

prefix=/usr
exec_prefix=${prefix}
sbindir=${exec_prefix}/sbin
bindir=${exec_prefix}/bin
libdir=${exec_prefix}/lib
sysconfdir=/etc
PACKAGE_NAME=GRUB
PACKAGE_TARNAME=grub
PACKAGE_VERSION=1.98+20100804-5ubuntu3.3
target_cpu=i386
platform=efi
host_os=linux-gnu
pkglibdir=${libdir}/`echo ${PACKAGE_TARNAME}/${target_cpu}-${platform} | sed ${transform}`
localedir=${prefix}/share/locale

self=`basename $0`

grub_mkimage=${bindir}/`echo grub-mkimage | sed ${transform}`
grub_mkdevicemap=${sbindir}/`echo grub-mkdevicemap | sed ${transform}`
grub_probe=${sbindir}/`echo grub-probe | sed ${transform}`
grub_editenv=${bindir}/`echo grub-editenv | sed ${transform}`
rootdir=
grub_prefix=`echo /boot/grub | sed ${transform}`
modules=

efibootmgr=`which efibootmgr 2>/dev/null || true`

no_floppy=
force_lba=
recheck=no
removable=no
debug=no
efi_quiet=

# Usage: usage
# Print the usage.
usage () {
    cat <<EOF
Usage: $self [OPTION]
Install GRUB on your EFI partition.

  -h, --help              print this message and exit
  -v, --version           print the version information and exit
  --modules=MODULES       pre-load specified modules MODULES
  --root-directory=DIR    install GRUB images under the directory DIR
                          instead of the root directory
  --grub-mkimage=FILE     use FILE as grub-mkimage
  --grub-mkdevicemap=FILE use FILE as grub-mkdevicemap
  --grub-probe=FILE       use FILE as grub-probe
  --no-floppy             do not probe any floppy drive
  --recheck               probe a device map even if it already exists
  --removable             the installation device is removable

$self copies GRUB images into the DIR/boot directory specified by
--root-directory.

Report bugs to <bug-grub@gnu.org>.
EOF
}

argument () {
  opt=$1
  shift

  if test $# -eq 0; then
      echo "$0: option requires an argument -- '$opt'" 1>&2
      exit 1
  fi
  echo $1
}

# Check the arguments.
while test $# -gt 0
do
    option=$1
    shift

    case "$option" in
    -h | --help)
	usage
	exit 0 ;;
    -v | --version)
	echo "$self (${PACKAGE_NAME}) ${PACKAGE_VERSION}"
	exit 0 ;;

    --modules)
        modules=`argument $option "$@"`; shift ;;
    --modules=*)
	modules=`echo "$option" | sed 's/--modules=//'` ;;

    --root-directory)
	rootdir=`argument $option "$@"`; shift ;;
    --root-directory=*)
	rootdir=`echo "$option" | sed 's/--root-directory=//'` ;;

    --grub-mkimage)
	grub_mkimage=`argument $option "$@"`; shift ;;
    --grub-mkimage=*)
	grub_mkimage=`echo "$option" | sed 's/--grub-mkimage=//'` ;;

    --grub-mkdevicemap)
	grub_mkdevicemap=`argument $option "$@"`; shift ;;
    --grub-mkdevicemap=*)
	grub_mkdevicemap=`echo "$option" | sed 's/--grub-mkdevicemap=//'` ;;

    --grub-probe)
	grub_probe=`argument $option "$@"`; shift ;;
    --grub-probe=*)
	grub_probe=`echo "$option" | sed 's/--grub-probe=//'` ;;

    --no-floppy)
	no_floppy="--no-floppy" ;;
    --recheck)
	recheck=yes ;;
    --removable)
	removable=yes ;;
    # This is an undocumented feature...
    --debug)
	debug=yes ;;
    # Intentionally undocumented; for compatibility only.
    -f | --force)
	;;
    *)
	echo "Unrecognized option \`$option'" 1>&2
	usage
	exit 1
	;;
    esac
done

# for make_system_path_relative_to_its_root()
. ${libdir}/grub/grub-mkconfig_lib

# If the debugging feature is enabled, print commands.
if test $debug = yes; then
    set -x
    efi_quiet=-q
fi

# Initialize these directories here, since ROOTDIR was initialized.
case "$host_os" in
netbsd* | openbsd*)
    # Because /boot is used for the boot block in NetBSD and OpenBSD, use /grub
    # instead of /boot/grub.
    grub_prefix=`echo /grub | sed ${transform}`
    bootdir=${rootdir}
    ;;
*)
    # Use /boot/grub by default.
    bootdir=${rootdir}/boot
    ;;
esac

grubdir=${bootdir}/`echo grub | sed ${transform}`
device_map=${grubdir}/device.map

# Check if GRUB is installed.
set $grub_mkimage dummy
if test -f "$1"; then
    :
else
    echo "$1: Not found." 1>&2
    exit 1
fi

set $grub_mkdevicemap dummy
if test -f "$1"; then
    :
else
    echo "$1: Not found." 1>&2
    exit 1
fi

# Get GRUB_DISTRIBUTOR.
if test -f ${sysconfdir}/default/grub ; then
    . ${sysconfdir}/default/grub
fi

# Find the EFI System Partition.
efidir=
if test -d ${bootdir}/efi; then
    install_device=`$grub_mkdevicemap --device-map=/dev/stdout | $grub_probe --target=device --device-map=/dev/stdin ${bootdir}/efi`
    # Is it a mount point?
    if test "x$install_device" != "x`$grub_mkdevicemap --device-map=/dev/stdout | $grub_probe --target=device --device-map=/dev/stdin ${bootdir}`"; then
	efidir=${bootdir}/efi
    fi
elif test -n "$rootdir" && test "x$rootdir" != "x/"; then
    # The EFI System Partition may have been given directly using
    # --root-directory.
    install_device=`$grub_mkdevicemap --device-map=/dev/stdout | $grub_probe --target=device --device-map=/dev/stdin ${rootdir}`
    # Is it a mount point?
    if test "x$install_device" != "x`$grub_mkdevicemap --device-map=/dev/stdout | $grub_probe --target=device --device-map=/dev/stdin ${rootdir}/..`"; then
	efidir=${rootdir}
    fi
fi

if test -n "$efidir"; then
    efi_fs=`$grub_probe --target=fs --device-map=${device_map} ${efidir}`
    if test "x$efi_fs" = xfat; then :; else
	echo "${efidir} doesn't look like an EFI partition." 1>&2
	efidir=
    fi
fi

if test -n "$efidir"; then
    # The EFI specification requires that an EFI System Partition must
    # contain an "EFI" subdirectory, and that OS loaders are stored in
    # subdirectories below EFI.  Vendors are expected to pick names that do
    # not collide with other vendors.  To minimise collisions, we use the
    # name of our distributor if possible.
    if test $removable = yes; then
	# The specification makes stricter requirements of removable
	# devices, in order that only one image can be automatically loaded
	# from them.  The image must always reside under /EFI/BOOT, and it
	# must have a specific file name depending on the architecture.
	efi_distributor=BOOT
	case "$target_cpu" in
	i386)
	    efi_file=BOOTIA32.EFI
	    ;;
	x86-64)
	    efi_file=BOOTX64.EFI
	    ;;
	# GRUB does not yet support these architectures, but they're defined
	# by the specification so we include them here to ease future
	# expansion.
	ia64)
	    efi_file=BOOTIA64.EFI
	    ;;
	arm)
	    efi_file=BOOTARM.EFI
	    ;;
	esac
    else
	efi_distributor="$(echo "$GRUB_DISTRIBUTOR" | tr '[A-Z]' '[a-z]' | cut -d' ' -f1)"
	if test -z "$efi_distributor"; then
	    efi_distributor=grub
	fi
	# It is convenient for each architecture to have a different
	# efi_file, so that different versions can be installed in parallel.
	case "$target_cpu" in
	i386)
	    efi_file=grubia32.efi
	    ;;
	x86-64)
	    efi_file=grubx64.efi
	    ;;
	# GRUB does not yet support these architectures, but they're defined
	# by the specification so we include them here to ease future
	# expansion.
	ia64)
	    efi_file=grubia64.efi
	    ;;
	arm)
	    efi_file=grubarm.efi
	    ;;
	*)
	    efi_file=grub.efi
	    ;;
	esac
	# TODO: We should also use efibootmgr, if available, to add a Boot
	# entry for ourselves.
    fi
    efidir="$efidir/EFI/$efi_distributor"
    mkdir -p "$efidir" || exit 1
else
    # We don't know what's going on.  Fall back to traditional
    # (non-specification-compliant) behaviour.
    efidir="$grubdir"
    efi_distributor=
    efi_file=grub.efi
fi

# Create the GRUB directory if it is not present.
mkdir -p "$grubdir" || exit 1

# If --recheck is specified, remove the device map, if present.
if test $recheck = yes; then
    rm -f $device_map
fi

# Create the device map file if it is not present.
if test -f "$device_map"; then
    :
else
    # Create a safe temporary file.
    test -n "$mklog" && log_file=`$mklog`

    $grub_mkdevicemap --device-map=$device_map $no_floppy || exit 1
fi

# Make sure that there is no duplicated entry.
tmp=`sed -n '/^([fh]d[0-9]*)/s/\(^(.*)\).*/\1/p' $device_map \
    | sort | uniq -d | sed -n 1p`
if test -n "$tmp"; then
    echo "The drive $tmp is defined multiple times in the device map $device_map" 1>&2
    exit 1
fi

# Copy the GRUB images to the GRUB directory.
for file in ${grubdir}/*.mod ${grubdir}/*.lst; do
    if test -f $file && [ "`basename $file`" != menu.lst ]; then
	rm -f $file || exit 1
    fi
done
for file in ${pkglibdir}/*.mod ${pkglibdir}/*.lst; do
    cp -f $file ${grubdir} || exit 1
done

# Copy gettext files
mkdir -p ${grubdir}/locale/
for dir in ${localedir}/* ${localedir}-langpack/*; do
    if test -f "$dir/LC_MESSAGES/grub.mo"; then
        cp -f "$dir/LC_MESSAGES/grub.mo" "${grubdir}/locale/${dir##*/}.mo"
    fi
done

# Write device to a variable so we don't have to traverse /dev every time.
grub_device=`$grub_probe --target=device --device-map=${device_map} ${grubdir}` || exit 1

if ! test -f ${grubdir}/grubenv; then
    $grub_editenv ${grubdir}/grubenv create
fi

# Create the core image. First, auto-detect the filesystem module.
fs_module=`$grub_probe --target=fs --device-map=${device_map} --device ${grub_device}`
if test "$efidir" != "$grubdir" || test "x$fs_module" = xfat; then :; else
    echo "${grubdir} doesn't look like an EFI partition." 1>&2
    exit 1
fi

# Then the partition map module.  In order to support partition-less media,
# this command is allowed to fail (--target=fs already grants us that the
# filesystem will be accessible).
partmap_module=
for x in `$grub_probe --target=partmap --device-map=${device_map} --device ${grub_device} 2> /dev/null`; do
   partmap_module="$partmap_module part_$x";
done

# Device abstraction module, if any (lvm, raid).
devabstraction_module=`$grub_probe --target=abstraction --device-map=${device_map} --device ${grub_device}`

# The order in this list is critical.  Be careful when modifying it.
modules="$modules $fs_module $partmap_module $devabstraction_module"

relative_grubdir=`make_system_path_relative_to_its_root ${grubdir}` || exit 1
if [ "x${relative_grubdir}" = "x" ] ; then
    relative_grubdir=/
fi

prefix_drive=
config_opt=

if [ "x${devabstraction_module}" = "x" ] ; then
    if [ x"${install_device}" != x ]; then
      if echo "${install_device}" | grep -qx "(.*)" ; then
        install_drive="${install_device}"
      else
        install_drive="`$grub_probe --target=drive --device-map=${device_map} --device ${install_device}`" || exit 1
      fi
      install_drive="`echo ${install_drive} | sed -e s/,[a-z0-9,]*//g`"
    fi
    grub_drive="`$grub_probe --target=drive --device-map=${device_map} --device ${grub_device}`" || exit 1

    # Strip partition number
    grub_partition="`echo ${grub_drive} | sed -e 's/^[^,]*,//; s/)$//'`"
    grub_drive="`echo ${grub_drive} | sed -e s/,[a-z0-9,]*//g`"
    if [ "x${grub_drive}" != "x${install_drive}" ] ; then
        uuid="`$grub_probe --target=fs_uuid --device ${grub_device}`"
        if [ "x${uuid}" = "x" ] ; then
          echo "You attempted a cross-disk install, but the filesystem containing ${grubdir} does not support UUIDs." 1>&2
          exit 1
        fi
        echo "search.fs_uuid ${uuid} root " > ${grubdir}/load.cfg
	echo 'set prefix=($root)'"${relative_grubdir}" >> ${grubdir}/load.cfg
	config_opt="-c ${grubdir}/load.cfg "
        modules="$modules search_fs_uuid"
    else
        # No grub-setup, so we need to hardcode the partition number in the
        # core image's prefix.
        prefix_drive="(,$grub_partition)"
    fi
else
    prefix_drive=`$grub_probe --target=drive --device ${grub_device}` || exit 1
fi

$grub_mkimage ${config_opt} -O ${target_cpu}-efi --output=${efidir}/${efi_file} --prefix=${prefix_drive}${relative_grubdir} $modules || exit 1

# Try to make this image bootable using the EFI Boot Manager, if available.
if test "$removable" = no && test -n "$efi_distributor" && \
   test -n "$efibootmgr"; then
    # On Linux, we need the efivars kernel modules.
    case "$host_os" in
    linux*)
	modprobe -q efivars 2>/dev/null || true
	;;
    esac

    # Delete old entries from the same distributor.
    for bootnum in `efibootmgr | grep '^Boot[0-9]' | \
		    fgrep -i " $efi_distributor" | cut -b5-8`; do
	efibootmgr $efi_quiet -b "$bootnum" -B
    done

    # Add a new entry for the image we just created.  efibootmgr needs to be
    # given the disk device and partition number separately, so we have to
    # fiddle about with grub-probe to get hold of this reasonably reliably.
    # Use fresh device map text to avoid any problems with stale data, since
    # all we need here is a one-to-one mapping.
    clean_devmap="$($grub_mkdevicemap --device-map=/dev/stdout)"
    efidir_drive="$(echo "$clean_devmap" | $grub_probe --target=drive --device-map=/dev/stdin "$efidir")"
    if test -z "$efidir_drive"; then
	echo "Can't find GRUB drive for $efidir; unable to create EFI Boot Manager entry." >&2
    else
	efidir_disk="$(echo "$clean_devmap" | grep "^$(echo "$efidir_drive" | sed 's/,[^)]*//')" | cut -f2)"
	efidir_part="$(echo "$efidir_drive" | sed 's/^([^,]*,[^0-9]*//; s/[^0-9].*//')"
	efibootmgr $efi_quiet -c -d "$efidir_disk" -p "$efidir_part" -w \
	    -L "$GRUB_DISTRIBUTOR" -l "\\EFI\\$efi_distributor\\$efi_file"
    fi
fi

# Prompt the user to check if the device map is correct.
echo "Installation finished. No error reported."
echo "This is the contents of the device map $device_map."
echo "Check if this is correct or not. If any of the lines is incorrect,"
echo "fix it and re-run the script \`$self'."
echo

cat $device_map

# Bye.
exit 0
