#!/bin/sh -efu

# Copyright 2013 Intel Corporation
# Author: Artem Bityutskiy
# License: GPLv2

#
# This is a simple script which installs gummiboot to the ESP and creates the
# gummiboot configuration files. This script requires a number of environment
# variables to be defined. Namely:
#
# 1. INSTALLERFW_PART_COUNT - count of partitions
# 2. INSTALLERFW_PARTX_MOUNTPOINT - mount point of partition number X
#    (0 <= X < $INSTALLERFW_PART_COUNT)
# 3. INSTALLERFW_PARTX_PARTUUID - GPT GUID (AKA PARTUUID) of partition number X
# 4. INSTALLERFW_MOUNT_PREFIX - where the target partitions are mounted (the
#    "root" directory of the file-system we install gummiboot to)

PROG="setup-efi-ivi"

# This is a helper function which prints an error message and exits
fatal()
{
	printf "%s\n" "$PROG: error: $1" 1>&2
	exit 1
}

# Make sure the installer framework variables are defined
[ "${INSTALLERFW_PART_COUNT:+x}" == "x" ] ||
       fatal "installer framework environment variables not found"

# Find the required root and boot parition parameters
pnum=0
root_partuuid=
boot_mountpoint=

while [ "$pnum" -lt "$INSTALLERFW_PART_COUNT" ]; do
	mountpoint="INSTALLERFW_PART${pnum}_MOUNTPOINT"
	mountpoint="$(eval printf "%s" '$'$mountpoint)"

	# Find out all the required data for the root and boot partition
	if [ "$mountpoint" == "/" ]; then
		root_partuuid="INSTALLERFW_PART${pnum}_PARTUUID"
		root_partuuid="$(eval printf "%s" '$'$root_partuuid)"
	# The boot parition has to be at "/boot"
	elif [ "$mountpoint" == "/boot" ]; then
		boot_mountpoint="$mountpoint"
	fi

	pnum="$((pnum+1))"
done

# Path to the gummiboot files
gummiboot_path="$INSTALLERFW_MOUNT_PREFIX/usr/lib/gummiboot"
# Make sure gummiboot is installed in the system
if ! ([ -f $gummiboot_path/gummibootia32.efi ] || \
      [ -f $gummiboot_path/gummibootx64.efi ]); then
	fatal "\"$gummiboot_path/gummiboot*.efi\" files not found!"
fi

# Get the ESP location
esp="$INSTALLERFW_MOUNT_PREFIX/$boot_mountpoint"

# Install gummiboot
mkdir -p "$esp/EFI/boot"
[ -f "$gummiboot_path/gummibootia32.efi" ] &&
	cp "$gummiboot_path/gummibootia32.efi" "$esp/EFI/boot/bootia32.efi"
[ -f "$gummiboot_path/gummibootx64.efi" ] &&
	cp "$gummiboot_path/gummibootx64.efi" "$esp/EFI/boot/bootx64.efi"

# Generate the list of installed kernels
kernels="$(ls -1 "$esp" | grep "^vmlinuz-" | sort -r)"
# Get the newest kernel
newest_kernel="$(printf "%s" "$kernels" | head -n1)"

# Create the gummiboot configuration file
mkdir -p "$esp/loader"

cat > "$esp/loader/loader.conf" <<-EOF
timeout 0
default $newest_kernel
EOF

# Create a gummiboot entry for each kernel
mkdir -p "$esp/loader/entries"
printf "%s\n" "$kernels" | while IFS= read -r kernel; do

	kernel_version="$(printf "%s" $kernel | sed -e 's/vmlinuz-\(.*\)/\1/')"

	cat > "$esp/loader/entries/$kernel.conf" <<-EOF
	title Tizen IVI 3.0
	version $kernel_version
	efi /$kernel
	options $INSTALLERFW_KERNEL_OPTS root=PARTUUID=$root_partuuid
	EOF
done
