#!/bin/sh

## Copyright (C) 2006-2013 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 [ "${EXTLINUX_OS_PROPER}" != "true" ]
then
	echo "I: os-proper disabled in /etc/default/extlinux: Skipping ${_EXTLINUX_DIRECTORY}/os-proper.cfg"
	exit 0
fi

if [ ! -e /usr/lib/syslinux/modules/bios/chain.c32 ]
then
	echo "I: /usr/lib/syslinux/modules/bios/chain.c32 - No such file: Skipping ${_EXTLINUX_DIRECTORY}/os-proper.cfg"
	exit 0
fi

if [ ! -x /usr/bin/os-prober ]
then
	echo "I: /usr/bin/os-prober - No such file: Skipping ${_EXTLINUX_DIRECTORY}/os-proper.cfg"
	exit 0
fi

cp -f /usr/lib/syslinux/modules/bios/chain.c32 "${_EXTLINUX_DIRECTORY}"

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


"

for _OS in $(os-prober | tr ' ' '^' | paste -s -d ' ')
do
	_DEVICE="$(echo ${_OS} | cut -d ':' -f 1)"
	_LONGNAME="$(echo ${_OS} | cut -d ':' -f 2 | tr '^' ' ')"
	_LABEL="$(echo ${_OS} | cut -d ':' -f 3 | tr '^' ' ')"
	_BOOT="$(echo ${_OS} | cut -d ':' -f 4)"

	if [ "${_BOOT}" != "chain" ]
	then
		continue
	fi

	if [ -z "${_LONGNAME}" ]
	then
		_LONGNAME="${_LABEL}"
	fi

	_NUMBER="${_NUMBER:-0}"

	echo "P: Writing config for ${_LONGNAME} on ${_DEVICE}..."

	_DEVICENAME="$(echo ${_DEVICE} | sed -e 's/^\/dev\/[sh]d//' -e 'y/abcdefghij/0123456789/' -e 's/./& /')"

	# Writing other os entry
	_CONFIG="${_CONFIG}

label o${_NUMBER}
	menu label Other OS, ${_LONGNAME} (on ${_DEVICE})"

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

	_CONFIG="${_CONFIG}
	kernel chain.c32
	append hd${_DEVICENAME}"

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

_NUMBER=""

Update "${_EXTLINUX_DIRECTORY}/os-prober.cfg" "${_CONFIG}"
