#!/bin/bash

set -e

. /usr/share/debconf/confmodule

clean_up ()
{
    if [ -n "$TMPDIR" ] && [ -d "$TMPDIR" ]; then
        umount "$TMPDIR"
        rmdir "$TMPDIR"
    fi
}

CHECK='2.04-1ubuntu26.2'

update_recovery_partition() {
    UPDATE=1
    [ -z "$1" ] && exit
    TMPDIR=$(mktemp -d)
    mount "$1" "$TMPDIR"
    trap clean_up EXIT
    cd "$TMPDIR" || exit
    for deb in ./pool/main/g/grub2/grub-efi-amd64_*_amd64.deb ./debs/grub-efi-amd64_*_amd64.deb; do
        if [ -e "$deb" ] && dpkg --compare-versions "$(dpkg-deb -f "$deb" Version)" ge "$CHECK"; then
            UPDATE=0
            break
        fi
    done
    if [ "$UPDATE" = 1 ]; then
        tar xvf /usr/share/oem-fix-misc-cnl-grub-boothole/boot.tar.xz
        [ ! -e "debs" ] && mkdir debs
        cp -v /usr/share/oem-fix-misc-cnl-grub-boothole/debs/*.deb ./debs/
        if [ -d 'efi.factory' ]; then
            cp -v /usr/share/oem-fix-misc-cnl-grub-boothole/efi/boot/grubx64.efi efi.factory/boot/grubx64.efi
        elif [ -d 'efi' ]; then
            cp -v /usr/share/oem-fix-misc-cnl-grub-boothole/efi/boot/grubx64.efi efi/boot/grubx64.efi
        fi
    else
        echo "GRUB in recovery partition is new enough. No need to update it."
    fi
    cd /
}

case "$1" in
    (configure)
        if dpkg-query -W -f='${Status}\n' dell-recovery 2>&1 | grep "install ok installed" >/dev/null 2>&1; then
            TARGET=$(python3 -c "import Dell.recovery_common as magic; target=magic.find_partition(); print(target.decode('utf8')) if type(target) is bytes else print(target)")
        elif dpkg-query -W -f='${Status}\n' ubuntu-recovery 2>&1 | grep "install ok installed" >/dev/null 2>&1; then
            TARGET=$(python3 -c "import ubunturecovery.recovery_common as magic; target=magic.find_partition('PQSERVICE'); print(target.decode('utf8')) if type(target) is bytes else print(target)")
        else
            TARGET=""
        fi
        update_recovery_partition "$TARGET"
    ;;
esac

#DEBHELPER#
