#!/bin/sh

## Copyright (C) 2006-2014 Daniel Baumann <mail@daniel-baumann.ch>
##
## 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 -e

. /usr/share/extlinux/extlinux-update.sh

if ! ls /boot/vmlinuz* 2>&1
then
	echo "I: /boot/vmlinuz* - No such files: Skipping ${_EXTLINUX_DIRECTORY}/linux.cfg"
	exit 0
fi

# Create linux.cfg
_CONFIG="\
## ${_EXTLINUX_DIRECTORY}/linux.cfg
##
## IMPORTANT WARNING
##
## The configuration of this file is generated automatically.
## Do not edit this file manually, use: extlinux-update


"

# Find linux versions
_VERSIONS="$(cd /boot && ls vmlinuz-* | grep -v .dpkg-tmp | sed -e 's|vmlinuz-||g' | sort -Vr)"

if [ "$(stat --printf %d /)" = "$(stat --printf %d /boot)" ]
then
	# / and /boot are on the same filesystem
	_BOOT_DIRECTORY="/boot"
else
	# / and /boot are not on the same filesystem
	_BOOT_DIRECTORY=""
fi


for _VERSION in ${_VERSIONS}
do
	echo "P: Writing config for /boot/vmlinuz-${_VERSION}..."

	_NUMBER="${_NUMBER:-0}"
	_ENTRY="${_ENTRY:-1}"

	if [ -e /boot/initrd.img-${_VERSION} ]
	then
		_INITRD="initrd=${_BOOT_DIRECTORY}/initrd.img-${_VERSION}"
	else
		_INITRD=""
	fi

	if echo ${EXTLINUX_ALTERNATIVES} | grep -q default
	then
		# Writing default entry
		_CONFIG="${_CONFIG}

label l${_NUMBER}
	menu label ${EXTLINUX_MENU_LABEL} ${_VERSION}"

		if [ "${EXTLINUX_DEFAULT}" = "l${_NUMBER}" ]
		then
			_CONFIG="${_CONFIG}
	menu default"
		fi

		_CONFIG="${_CONFIG}
	linux ${_BOOT_DIRECTORY}/vmlinuz-${_VERSION}
	append ${_INITRD} ${EXTLINUX_ROOT} ${EXTLINUX_PARAMETERS}"
	fi

	if echo ${EXTLINUX_ALTERNATIVES} | grep -q live
	then
		# Writing live entry
		_CONFIG="${_CONFIG}

label l${_NUMBER}l
	menu label ${EXTLINUX_MENU_LABEL} ${_VERSION} (live mode)"

		if [ "${EXTLINUX_DEFAULT}" = "l${_NUMBER}l" ]
		then
			_CONFIG="${_CONFIG}
	menu default"
		fi

		_CONFIG="${_CONFIG}
	linux ${_BOOT_DIRECTORY}/vmlinuz-${_VERSION}
	append ${_INITRD} ${EXTLINUX_ROOT} ${EXTLINUX_PARAMETERS} boot=live plainroot
	text help
   This option boots the system into live mode (non-persistent)
	endtext"
	fi

	if echo ${EXTLINUX_ALTERNATIVES} | grep -q recovery
	then
		# Writing recovery entry
		_CONFIG="${_CONFIG}

label l${_NUMBER}r
	menu label ${EXTLINUX_MENU_LABEL} ${_VERSION} (recovery mode)"

		if [ "${EXTLINUX_DEFAULT}" = "l${_NUMBER}r" ]
		then
			_CONFIG="${_CONFIG}
		menu default"
		fi

		_CONFIG="${_CONFIG}
	linux ${_BOOT_DIRECTORY}/vmlinuz-${_VERSION}
	append ${_INITRD} ${EXTLINUX_ROOT} $(echo ${EXTLINUX_PARAMETERS} | sed -e 's| quiet||') single
	text help
   This option boots the system into recovery mode (single-user)
	endtext"
	fi

	_NUMBER="$((${_NUMBER} + 1))"

	if [ "${EXTLINUX_ENTRIES}" = "${_ENTRY}" ]
	then
		break
	fi
done

_NUMBER=""

Update "${_EXTLINUX_DIRECTORY}/linux.cfg" "${_CONFIG}"
