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

#  SPDX-License-Identifier: LGPL-2.1+
#
#  Copyright © 2020-2021 Collabora Ltd.
#  Copyright © 2020-2021 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 -euo pipefail

fail() { echo >&2 "$@"; exit 1; }

usage() {
    local status=${1-2}

    if [ $status -ne 0 ]; then
        exec >&2
    fi

    echo
    echo "Usage: $(basename $0) [OPTION]"
    echo
    echo "A wrapper around grub-mkconfig, applying extra magic on top."
    echo
    echo "OPTIONS"
    echo
    echo "  -h, --help"
    echo "        This help screen."
    echo

    exit $status
}

prepare_grub_to_access_device() {
    set -- prepare_grub_to_access_device "$@"
    "$SHELL" -c '. /usr/share/grub/grub-mkconfig_lib; "$@"' "$0" "$@"
}

grubcfg() {
    cat <<EOF
#
# Automatically generated file; DO NOT EDIT.
# ${0##*/} grub.cfg
#

EOF

    device="$(grub-probe --target=device "$1")"
    prepare_grub_to_access_device "$device"

    cat <<EOF
configfile $1
EOF
}

parse_args() {
    while (( $# > 0 )); do
        case "$1" in
            -h|--help)
                usage 0
                ;;
            *)
                usage 1
                ;;
        esac
    done
}

parse_args "$@"

if [[ "$(id -u)" -ne 0 ]]; then
    fail "${0##*/}: You must run this as root"
fi

CDIR=$(mktemp -d);
grub-mkconfig -o "$CDIR"/grub.cfg

file=/efi/EFI/steamos/grub.cfg
mkdir -p "${file%/*}"

echo "Installing grub configuration file to /efi..." >&2
if ! mv "$CDIR"/grub.cfg /boot/grub/grub.cfg 2>/dev/null; then
    # If we can't move the config file into the non-EFI location
    # then move it directly to the EFI location and boot from there
    echo "Warning: /boot/grub/grub.cfg: Read-only file" >&2
    mv "$CDIR"/grub.cfg $file
else
    # If we did move the config to the non-EFI location generate
    # a minimal grub config wrapper that lets the EFI grub binary
    # read the config from the OS filesystem
    grubcfg /boot/grub/grub.cfg > $file
fi

rmdir "$CDIR"

