#!/bin/sh

## live-build(7) - System Build Scripts
## Copyright (C) 2015 Matthias Klumpp <mak@debian.org>
## Copyright (C) 2016 Jonathan Riddell <mak@debian.org>
##
## This program comes with ABSOLUTELY NO WARRANTY; for details see COPYING.
## This is free software, and you are welcome to redistribute it
## under certain conditions; see COPYING for details.

set -ex

# Including common functions
[ -e "${LIVE_BUILD}/scripts/build.sh" ] && . "${LIVE_BUILD}/scripts/build.sh" || . /usr/lib/live/build.sh

# Setting static variables
DESCRIPTION="$(Echo 'prepares and installs EFI support into binary')"
HELP=""
USAGE="${PROGRAM} [--force]"

Arguments "${@}"

# Reading configuration files
Read_conffiles config/all config/common config/bootstrap config/chroot config/binary config/source
Set_defaults

case "${LB_ARCHITECTURES}" in
	amd64)
		_EFI_TYPE=efi64
		;;
	i386)
		echo "WARNING: We don't support EFI on ${LB_ARCHITECTURES} yet." >&2
		exit 0
		;;
	*)
		echo "ERROR: can't provide EFI boot support to architecture ${LB_ARCHITECTURES}" >&2
		exit 1
		;;
esac

Echo_message "Begin preparing EFI support..."

# Requiring stage file
Require_stagefile .build/config .build/bootstrap

# Checking stage file
Check_stagefile .build/binary_efi

# Checking lock file
Check_lockfile .lock

# Creating lock file
Create_lockfile .lock

# Check architecture
Check_architectures amd64 i386
Check_crossarchitectures

# Checking depends
case "${LB_BUILD_WITH_CHROOT}" in
	true)
		Check_package chroot /usr/bin/mcopy mtools
		;;

	false)
		if [ ! -e /usr/bin/mcopy ]
		then
			# mtools
			Echo_error "/usr/bin/mcopy - no such file."
			exit 1
		fi
		;;
esac

# Restoring cache
Restore_cache cache/packages.binary

# Installing depends
Install_package

mkdir -p binary/boot/grub/
cp -r /usr/share/live/build/bootloaders/grub-efi/* binary/boot/grub/

# Move GRUB files to the right place.
mkdir -p binary/EFI/BOOT
mcopy -n -i binary/boot/grub/efi.img ::EFI/BOOT/BOOTx64.EFI binary/EFI/BOOT/BOOTx64.EFI
mcopy -n -i binary/boot/grub/efi.img ::EFI/BOOT/grubx64.efi binary/EFI/BOOT/grubx64.efi || true

# needed for ubiquity's efi setup to use the live image as an archive from which various bits can install
# see d-i/source/apt-setup/generators/40cdrom
mkdir -p binary/.disk/ || true
echo full_cd/single > binary/.disk/cd_type

case "${LB_BUILD_WITH_CHROOT}" in
        true)
                # Saving cache
                Save_cache cache/packages.binary

                # Removing depends
                Remove_package
                ;;
esac

# Creating stage file
Create_stagefile .build/binary_efi
