#! /bin/sh

set -e

. /usr/share/proxmox-kernel-helper/scripts/functions

if proxmox-boot-tool status --quiet; then
    # detect when being called by dpkg (e.g. grub-pc.postinst
    if [ -n "$DPKG_RUNNING_VERSION" ] && echo "$DPKG_MAINTSCRIPT_PACKAGE" | grep -sq -e "^grub-" -e "^shim-"; then
            MARKER_FILE="/tmp/proxmox-boot-tool.dpkg.marker"
            if [ ! -e "$MARKER_FILE" ]; then
                warn "This system is booted via proxmox-boot-tool, running proxmox-boot-tool init for all configured bootdisks"
                # can fail for various reasons, but we don't want to fail the upgrade..
                proxmox-boot-tool reinit || true
                proxmox-boot-tool refresh || true
                touch "$MARKER_FILE"
                exit 0
            else
                echo "Proxmox's boot-tool marker file found, ignoring grub install call."
                exit 0
            fi
    fi
    warn "grub-install is disabled because this system is booted via proxmox-boot-tool, if you really need to run it, run /usr/sbin/grub-install.real"
    exit 1
else
    grub-install.real "$@"
fi
