#!/bin/sh
# -*- mode: sh; indent-tabs-mode: nil; sh-basic-offset: 2; -*-
# vim: et sts=2 sw=2

#  SPDX-License-Identifier: LGPL-2.1+
#
#  Copyright © 2020 Collabora Ltd.
#  Copyright © 2020 Valve Corporation.
#
#  This file is part of steamos-customizations.
#
#  steamos-customizations is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation; either version 2.1 of the License,
#  or (at your option) any later version.

set -e

if [ "x${GRUB_DISABLE_EFI_PROBER}" = "xtrue" ]; then
  exit 0
fi

isremovable() {
    if ! devname="$(realpath "$1")"; then
        return 1
    fi

    if ! devpath="$(realpath "/sys/class/block/${devname##*/}")"; then
        return 1
    fi

    if ! test -e "$devpath/removable"; then
        devpath="${devpath%/*}"
    fi

    if ! test -e "$devpath/removable"; then
        return 1
    fi

    grep -q 1 "$devpath/removable"
}

# If we're _not_ on removable media (ie not running from the
# installer) then don't probe known EFI locations/variables either.
if ! isremovable /dev/disk/by-partsets/self/rootfs; then
  exit 0
fi

cat <<EOF
submenu 'Other EFI Loaders' "\$menuentry_id_option" 'efi' {
	for efi in (*,gpt*)/EFI/steamos/steamcl.efi; do
		regexp --set=1:efi_root '^\\((.*)\\)/' "\${efi}"
		if [ -e "\${efi}" ]; then
			menuentry --class=efi "\${efi}" "\${efi_root}" {
				root="\${2}"
				chainloader "\${1}"
			}
		fi
	done
}
EOF
