#! /bin/bash -e

# update-grub helper script.
# Copyright (C) 2006,2007,2008  Free Software Foundation, Inc.
#
# GRUB 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 GRUB.  If not, see <http://www.gnu.org/licenses/>.

prefix=/usr
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
. ${libdir}/grub/update-grub_lib

if [ "x${GRUB_DISTRIBUTOR}" = "x" ] ; then
  OS=GNU/Linux
else
  OS="${GRUB_DISTRIBUTOR} GNU/Linux"
fi

# loop-AES arranges things so that /dev/loop/X can be our root device, but
# the initrds that Linux uses don't like that.
case ${GRUB_DEVICE} in
  /dev/loop/*|/dev/loop[0-9])
    GRUB_DEVICE=`losetup ${GRUB_DEVICE} | sed -e "s/^[^(]*(\([^)]\+\)).*/\1/"`
  ;;
esac

if [ "x${GRUB_DEVICE_UUID}" = "x" ] || [ "x${GRUB_DISABLE_LINUX_UUID}" = "xtrue" ] \
    || ! test -e "/dev/disk/by-uuid/${GRUB_DEVICE_UUID}" \
    || [ "`grub-probe -t abstraction --device ${GRUB_DEVICE}`" != "" ] ; then
  LINUX_ROOT_DEVICE=${GRUB_DEVICE}
else
  LINUX_ROOT_DEVICE=UUID=${GRUB_DEVICE_UUID}
fi

test_numeric ()
{
  local a=$1
  local cmp=$2
  local b=$3
  if [ "$a" = "$b" ] ; then
    case $cmp in
      ge|eq|le) return 0 ;;
      gt|lt) return 1 ;;
    esac
  fi
  if [ "$cmp" = "lt" ] ; then
    c=$a
    a=$b
    b=$c
  fi
  if (echo $a ; echo $b) | sort -n | head -n 1 | grep -qx $b ; then
    return 0
  else
    return 1
  fi
}

### This function taken from GRUB Legacy's update-grub

# Compares two version strings A and B
# Returns -1 if A<B
#          0 if A==B
#          1 if A>B
# This compares version numbers of the form
# 2.4.14.2 > 2.4.14
# 2.4.14random = 2.4.14-random > 2.4.14-ac10 > 2.4.14 > 2.4.14-pre2 > 
# 2.4.14-pre1 > 2.4.13-ac99
CompareVersions()
{  
    	#Changes the line something-x.y.z into somthing-x.y.z.q
	#This is to ensure that kernels with a .q is treated as higher than the ones without               
        #First a space is put after the version number
        v1=$(echo $1 | sed -e 's!^\(.*-\([0-9]\+\.\)\{2,3\}[0-9]\+\)\(.*\)!\1 \3!g')
	v2=$(echo $2 | sed -e 's!^\(.*-\([0-9]\+\.\)\{2,3\}[0-9]\+\)\(.*\)!\1 \3!g')
	#If the version number only has 3 digits then put in another .0
        v1=$(echo $v1 | sed -e 's!^\(.*-\([0-9]\+\.\)\{2\}[0-9]\+\)\( .*\|$\)!\1.0 \3!g')
        v2=$(echo $v2 | sed -e 's!^\(.*-\([0-9]\+\.\)\{2\}[0-9]\+\)\( .*\|$\)!\1.0 \3!g')
          
	# Then split the version number and remove any '.' 's or dashes
	v1=$(echo $v1 | sed -e 's![-\.]\+! !g' -e 's!\([0-9]\)\([[:alpha:]]\)!\1 \2!')
	v2=$(echo $v2 | sed -e 's![-\.]\+! !g' -e 's!\([0-9]\)\([[:alpha:]]\)!\1 \2!')

	# we weight different kernel suffixes here
	# ac   = 50
	# pre  = -50
	# rc   = -40
	# test = -60
	# others are given 99
	v1=$(echo $v1 | sed -e 's! k7! 786 !g' -e 's! ac! 50 !g' -e 's! rc! -40 !g' -e 's! pre! -50 !g' -e 's! test! -60 !g' -e 's![^ ]*[^-0-9 ][^ ]*!99!g')

	v2=$(echo $v2 | sed -e 's! k7! 786 !g' -e 's! ac! 50 !g' -e 's! rc! -40 !g' -e 's! pre! -50 !g' -e 's! test! -60 !g' -e 's![^ ]*[^-0-9 ][^ ]*!99!g')

	result=0; v1finished=0; v2finished=0;
	while [ $result -eq 0 ] && [ $v1finished -eq 0 ] && [ $v2finished -eq 0 ];
	do
		if [ "$v1" = "" ]; then
			v1comp=0; v1finished=1
		else
			set -- $v1; v1comp=$1; shift; v1=$*
		fi

		if [ "$v2" = "" ]; then
			v2comp=0; v2finished=1
		else
			set -- $v2; v2comp=$1; shift; v2=$*
		fi
		
		set +e
		result=`expr $v1comp - $v2comp` 
		result=`expr substr $result 1 2`
		set -e

		if   [ $result -gt 0 ]; then result=1
		elif [ $result -lt 0 ]; then result=-1	
		fi	
	done

	# finally return the result
	echo $result
}

test_gt ()
{
  local a=`echo $1 | sed -e "s/vmlinu[zx]-//g"`
  local b=`echo $2 | sed -e "s/vmlinu[zx]-//g"`
  [ `CompareVersions "$a" "$b"` == 1 ]
  return $?
}

find_latest ()
{
  local a=""
  for i in $@ ; do
    if test_gt "$i" "$a" ; then
      a="$i"
    fi
  done
  echo "$a"
}

list=`for i in /boot/vmlinu[xz]-* /vmlinu[xz]-* ; do
        if grub_file_is_not_garbage "$i" ; then echo -n "$i " ; fi
      done`

if [ "x$list" != "x" ] ; then
  prepare_grub_to_access_device ${GRUB_DEVICE_BOOT}
fi

while [ "x$list" != "x" ] ; do
  linux=`find_latest $list`
  echo "Found linux image: $linux" >&2
  basename=`basename $linux`
  dirname=`dirname $linux`
  rel_dirname=`make_system_path_relative_to_its_root $dirname`
  version=`echo $basename | sed -e "s,^[^0-9]*-,,g"`
  alt_version=`echo $version | sed -e "s,\.old$,,g"`
  linux_root_device_thisversion="${LINUX_ROOT_DEVICE}"

  initrd=
  for i in "initrd.img-${version}" "initrd-${version}.img" \
	   "initrd.img-${alt_version}" "initrd-${alt_version}.img"; do
    if test -e "${dirname}/${i}" ; then
      initrd="$i"
      break
    fi
  done
  if test -n "${initrd}" ; then
    echo "Found initrd image: ${dirname}/${initrd}" >&2
  else
    # "UUID=" magic is parsed by initrds.  Since there's no initrd, it can't work here.
    linux_root_device_thisversion=${GRUB_DEVICE}
  fi

  cat << EOF
menuentry "${OS}, linux ${version}" {
	linux	${rel_dirname}/${basename} root=${linux_root_device_thisversion} ro ${GRUB_CMDLINE_LINUX} ${GRUB_CMDLINE_LINUX_DEFAULT}
EOF
  if test -n "${initrd}" ; then
    cat << EOF
	initrd	${rel_dirname}/${initrd}
EOF
  fi
  cat << EOF
}
EOF

  cat << EOF
menuentry "${OS}, linux ${version} (single-user mode)" {
	linux	${rel_dirname}/${basename} root=${linux_root_device_thisversion} ro single ${GRUB_CMDLINE_LINUX}
EOF
  if test -n "${initrd}" ; then
    cat << EOF
	initrd	${rel_dirname}/${initrd}
EOF
  fi
  cat << EOF
}
EOF

  list=`echo $list | tr ' ' '\n' | grep -vx $linux | tr '\n' ' '`
done
