#!/bin/bash -ex
#
# setup-bootloader - Install bootloader in the boot disk
#
# Author: Alexsander de Souza <alexsander.souza@canonical.com>
#
# Copyright (C) 2024 Canonical
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

export DEBIAN_FRONTEND=noninteractive

# Clean up remnants from packer-maas vm install
rm /var/cache/debconf/config.dat
dpkg --configure -a

# Update the package lists before attempting to install the kernel
apt-get update
# Ensure the existence of linux-image-generic for non-cloudimg images.
apt-get -y install linux-image-generic

ARCH=$(dpkg --print-architecture)

dpkg-reconfigure grub-efi-${ARCH}
update-grub

if [ ${ARCH} == "amd64" ]; then
    GRUB_TARGET="x86_64-efi"
else
    GRUB_TARGET="arm64-efi"
fi

grub-install \
    --target=${GRUB_TARGET} \
    --efi-directory=/boot/efi \
    --bootloader-id=ubuntu \
    --recheck

update-initramfs -uk all

efibootmgr -v
