#!/bin/sh
set -e

# grub-mkconfig helper script.
# Copyright (C) 2011-2014  Equipe EOLE <eole@ac-dijon.fr>
#
# eole-common is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GRUB is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with eole-kernel-version.  If not, see <http://www.gnu.org/licenses/>.

# This script will set the default entry used by grub based on local
# configuration in /usr/share/eole/noyau/local.

prefix=/usr
exec_prefix=${prefix}
bindir=${exec_prefix}/bin
libdir=${exec_prefix}/lib
. ${libdir}/grub/grub-mkconfig_lib

EOLE_GRUB_REGEX=invalid-kernel-regexp
EOLE_KERNEL_DIR=/usr/share/eole/noyau
EOLE_KERNEL_LOCAL=${EOLE_KERNEL_DIR}/local

INITRD_DIR=/var/lib/initramfs-tools

# If no local kernel config, back to default
grub-set-default 0

# No local kernel
test -f "${EOLE_KERNEL_LOCAL}" || exit 0

EOLE_GRUB_REGEX=$(head -n1 "${EOLE_KERNEL_LOCAL}")
if test -z "${EOLE_GRUB_REGEX}"
then
    echo "Empty local kernel configuration file ${EOLE_KERNEL_LOCAL}." >&2
    exit 0
fi
list=`for i in /boot/vmlinu[xz]-* /vmlinu[xz]-* /boot/kernel-* ; do
    if grub_file_is_not_garbage "$i" ; then echo -n "$i " ; fi
    done`

in_submenu=false
submenu=""
while [ "x$list" != "x" ] ; do
    linux=`version_find_latest $list`
    if $(echo -n ${linux} | grep -qP "${EOLE_GRUB_REGEX}")
    then
	basename=`basename $linux`
	version=`echo $basename | sed -e "s,^[^0-9]*-,,g"`
	version_title=`grep "menuentry.*${version}" /boot/grub/grub.cfg | cut -d "'" -f4 | head -n 1`
	echo "Found default kernel '${submenu}${version_title}' matching '${EOLE_GRUB_REGEX}'" >&2
	test -x /usr/sbin/grub-set-default && grub-set-default "${submenu}${version_title}" >&2
	test -d ${EOLE_KERNEL_DIR} \
	    && echo ${version} >| ${EOLE_KERNEL_DIR}/current
	test -d ${INITRD_DIR} && ! test -f ${INITRD_DIR}/${version} \
	    && echo ${version} > ${INITRD_DIR}/${version}
	break
    fi
    if [ "$list" ] && ! $in_submenu; then
    submenu="$(gettext_printf "Advanced options for %s" "${GRUB_DISTRIBUTOR} GNU/Linux")>"
	in_submenu=:
    fi
    list=`echo $list | tr ' ' '\n' | grep -vx $linux | tr '\n' ' '`
done
