#!/bin/bash
# grub-mkconfig helper script
# 
# Copyright (c) 2009-2013 by Silvan Calarco <silvan.calarco@mambasoft.it>
# Released under the terms of the GNU/GPL v.3 license
#

prefix=/usr
exec_prefix=/usr
datarootdir="${prefix}/share"
. "${datarootdir}/grub/grub-mkconfig_lib"

mountpoints=`cat /proc/mounts |grep " /mnt/" | awk '{ print $2; }'`

for mountpoint in $mountpoints; do
   [ "$mountpoint" != "/" -a -e $mountpoint/boot/ ] && {
      grubdrive=`/usr/sbin/grub-probe -t drive $mountpoint`
      for f in $mountpoint/boot/grub/menu.lst $mountpoint/boot/grub/grub.conf $mountpoint/boot/grub/grub.cfg; do
         if [ -r $f ]; then
            kernel=`grep -m1 -i vmlinuz $f | awk '{ print $2 }' | sed "s|(.*)||"`
            kernel_opts=`grep -m1 -i vmlinuz $f | awk '{ print $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22 }'`
            initramfs=`grep -m1 -i initramfs $f | awk '{ print $2 }' | sed "s|(.*)||"`
            [ $initramfs ] || initramfs=`grep -m1 -i initrd $f | awk '{ print $2 }' | sed "s|(.*)||"`
            title=`grep -m1 -i title $f | sed "s|title[[:space:]]*||"` || \
            title=`grep -m1 -i menuentry $f | awk '{ print $2 }' | sed "s|(.*)||"`
            title=`echo $title | sed "s|^_||" | sed "s|_$||"`
            # skip other recovery entries
            echo "$title" | grep -i recover >/dev/null && continue
            [ "$title" ] || title="Linux ${kernel/*\//} on $grubdrive"
            [ $kernel ] && {
               echo "Found other linux image: $kernel" >&2
               cat << EOF
menuentry "${title}" {
EOF
               save_default_entry | sed -e "s/^/\t/"
               cat << EOF
        linux   ${grubdrive}${kernel} ${kernel_opts}
EOF
               if test -n "${initramfs}" ; then
                  echo "Found other linux initrd image: ${initramfs}" >&2
                  cat << EOF
        initrd  ${grubdrive}${initramfs}
EOF
                  cat << EOF
}
EOF
               fi
               break
            }
         fi
      done
   }
done
exit 0
