#!/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 "Run grub-mkconfig and place output at /efi/EFI/steamos/grub.cfg"
    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" "$@"
}

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);

if grub-mkconfig -o "$CDIR"/grub.cfg; then
    file=/efi/EFI/steamos/grub.cfg
    mkdir -p "${file%/*}"
    echo "Installing grub configuration file at $file" >&2
    mv "$CDIR"/grub.cfg $file
else
    rc=$?
    echo "Failed to generate grub configuration at $CDIR/grub.cfg"
    exit $rc
fi

rmdir "$CDIR"

