#!/bin/sh

if ! which ostree >/dev/null 2>/dev/null; then
    exit 0
fi
if ! test -d /ostree/repo; then
    exit 0
fi

# Gracefully exit if we can not find the grub2 'default' configuration as it is
# the case on new installations with bootupd where it is not needed.
if ! test -f /etc/default/grub; then
    exit 0
fi

# Gracefully exit if the grub2 configuration has BLS enabled,
# and the installed version has support for the blscfg module.
# Since there is no need to create menu entries for that case.
# See: https://src.fedoraproject.org/rpms/grub2/c/7c2bab5e98d
. /etc/default/grub
if [ -d /etc/default/grub.d ]; then
    for script in /etc/default/grub.d/*; do
        if [ -f "$script" ]; then
            . "$script"
            if [ $? -ne 0 ]; then
                exit 1
            fi
        fi
    done
fi


if test -f /boot/grub2/.grub2-blscfg-supported && \
   test "${GRUB_ENABLE_BLSCFG}" = "true"; then
   exit 0
fi

# Make sure we're in the right environment
if ! test -n "${GRUB_DEVICE}"; then
    echo "This script must be run as a child of grub2-mkconfig" 1>&2
    exit 1
fi

set -e

# Pick up stuff from grub's helper that we want to inject into our
# generated bootloader configuration.  Yes, this is pretty awful, but
# it's a lot better than reimplementing the config-generating bits of
# OSTree in shell script.

. /usr/share/grub/grub-mkconfig_lib

DEVICE=${GRUB_DEVICE_BOOT:-${GRUB_DEVICE}}

GRUB2_BOOT_DEVICE_ID="$(grub_get_device_id ${DEVICE})"
export GRUB2_BOOT_DEVICE_ID
GRUB2_PREPARE_ROOT_CACHE="$(prepare_grub_to_access_device ${DEVICE})"
export GRUB2_PREPARE_ROOT_CACHE

# Refer to the processing of ostree deploy, the purpose is to be compatible with the scenario of whether boot is partitioned independently
if [ ! -L /boot/boot ]; then
    ln -s . /boot/boot
fi
exec deepin-immutable-ctl admin grub-entry
