#!/bin/sh -efu

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

# This scripts then scans the boot partition, finds out which kernels are
# available, and updates the extlinux configuration file: adds missing kernel
# records and delets non-existing kernels records. The default boot kernel is
# always the one with the latest version.
#
# This scripts makes several assumptions.
# 1. There is already a valid extlinux configuration at the boot partition
# 2. The kernel binary names are 'vmlinuz-<version>'
# 3. Extlinux uses the kernel pointed to by the "vmlinuz" symlink

PROG="setup-extlinux-conf"

# This is a helper function which printfs 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_MOUNT_PREFIX:+x}" == "x" ] ||
       fatal "installer framework environment variables not found"

# Get the boot directory path
boot_path="$INSTALLERFW_MOUNT_PREFIX/boot"

# Make sure the extlinux configuration file exists
conf_file="$boot_path/extlinux/extlinux.conf"
[ -f "$conf_file" ] || \
	fatal "cannot find the extlinux configuration file (\"$conf_file\")"

# Get the newest installed kernel
newest_kernel="$(ls -1 "$boot_path" | grep '^vmlinuz-' | sort -r | head -n1)"
[ -n "$newest_kernel" ] || \
	fatal "no vmlinuz-* files found in \"$boot_path\""

# Update the "vmlinuz" symlink
ln -sf "$newest_kernel" "$boot_path/vmlinuz" || \
	fatal "cannot create symlink: $boot_path/vmlinuz --> $newest_kernel
