# Snapd-Boot-Config-Edition: 1

set default=0
set timeout=3
set timeout_style=hidden

if [ -e /EFI/ubuntu/grubenv ]; then
   load_env --file /EFI/ubuntu/grubenv snapd_recovery_mode snapd_recovery_system
fi

# standard cmdline params
set snapd_static_cmdline_args='console=ttyS0 console=tty1 panic=-1'

# if no default boot mode set, pick one
if [ -z "$snapd_recovery_mode" ]; then
    set snapd_recovery_mode=install
fi

if [ "$snapd_recovery_mode" = "run" ]; then
    default="run"
elif [ -n "$snapd_recovery_system" ]; then
    default=$snapd_recovery_mode-$snapd_recovery_system
fi

search --no-floppy --set=boot_fs --label ubuntu-boot

if [ -n "$boot_fs" ]; then
    menuentry "Continue to run mode" --hotkey=n --id=run {
        chainloader ($boot_fs)/EFI/boot/grubx64.efi
    }
fi

# globbing in grub does not sort
for label in /systems/*; do
    regexp --set 1:label "/([0-9]*)\$" "$label"
    if [ -z "$label" ]; then
        continue
    fi
    # yes, you need to backslash that less-than
    if [ -z "$best" -o "$label" \< "$best" ]; then
        set best="$label"
    fi
    # if grubenv did not pick mode-system, use best one
    if [ -z "$snapd_recovery_system" ]; then
        default=$snapd_recovery_mode-$best
    fi
    set snapd_recovery_kernel=
    load_env --file /systems/$label/grubenv snapd_recovery_kernel snapd_extra_cmdline_args

    # We could "source /systems/$snapd_recovery_system/grub.cfg" here as well
    menuentry "Recover using $label" --hotkey=r --id=recover-$label $snapd_recovery_kernel recover $label {
        loopback loop $2
        chainloader (loop)/kernel.efi snapd_recovery_mode=$3 snapd_recovery_system=$4 $snapd_static_cmdline_args $snapd_extra_cmdline_args
    }
    menuentry "Install using $label" --hotkey=i --id=install-$label $snapd_recovery_kernel install $label {
        loopback loop $2
        chainloader (loop)/kernel.efi snapd_recovery_mode=$3 snapd_recovery_system=$4 $snapd_static_cmdline_args $snapd_extra_cmdline_args
    }
done

menuentry 'UEFI Firmware Settings' --hotkey=f 'uefi-firmware' {
    fwsetup
}
