#!/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.1'

update_recovery_partition() {
    UPDATE=1
    [ -z "$1" ] && exit
    TMPDIR=$(mktemp -d)
    mount "$1" "$TMPDIR"
    trap clean_up EXIT
    cd "$TMPDIR" || exit
    # Need latest ubuntu-recovery to fix that grub's packages couldn't be update.
    # Example: sutton-newell-focal-amd64-20200720-61
    project=`tail -n1 ./.disk/buildstamp | grep -o '^[^-]\+-[^-]\+'`
    if [ "$project" = "sutton-newell" ] || [ "$project" = "sutton-simon" ] ; then
        [ ! -e "debs" ] && mkdir debs
        cp -v /usr/share/oem-fix-misc-cnl-grub-boothole/debs/ubuntu-recovery*.deb ./debs/
    fi
    for deb in ./pool/main/g/grub2/grub-efi_*_amd64.deb ./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/grub*.deb ./debs/
    fi
    for efi in efi.factory/boot/grubx64.efi efi/boot/grubx64.efi; do
        if [ -f "$efi" ]; then
            VERSION=$(strings "$efi" | grep "${CHECK:0:12}")
            if dpkg --compare-versions "$VERSION" lt "$CHECK"; then
                cp -v /usr/share/oem-fix-misc-cnl-grub-boothole/efi/boot/grubx64.efi "$efi"
                UPDATE=1
                break
            fi
        fi
    done
    if [ "$UPDATE" = 0 ]; then
        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' 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)")
        elif 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)")
        else
            TARGET=""
        fi
        update_recovery_partition "$TARGET"
    ;;
esac

#DEBHELPER#
