#!/bin/sh

set -e

. /usr/lib/grub/grub-mkconfig_lib

CLASS="--class gnu-linux --class gnu --class os"

if [ "x${GRUB_DEVICE_UUID}" = "x" ] || [ "x${GRUB_DISABLE_LINUX_UUID}" = "xtrue" ] \
    || ! test -e "/dev/disk/by-uuid/${GRUB_DEVICE_UUID}" \
    || uses_abstraction "${GRUB_DEVICE}" lvm; then
  LINUX_ROOT_DEVICE=${GRUB_DEVICE}
else
  LINUX_ROOT_DEVICE=UUID=${GRUB_DEVICE_UUID}
fi

ostree_linux_entry ()
{
  os="$1"
  version="$2"
  args="$3"

  printf "menuentry '${os}; Linux ${version}' ${CLASS} {\n"

  cat << EOF
	insmod gzio
EOF

  cat <<EOF
	echo '"Loading ${os} ${version}"'
	linux ${rel_dirname}/${basename} root=${linux_root_device_thisversion} ro ostree=current ${args}
EOF
  if test -n "${initrd}" ; then
    message="$(gettext_printf "Loading initial ramdisk ...")"
    cat << EOF
	echo	'$message'
	initrd	${rel_dirname}/${initrd}
EOF
  fi
  cat << EOF
}
EOF
}

kernels=$(echo /boot/vmlinuz-*)
while [ "x${kernels}" != x ]; do
  linux=`version_find_latest $kernels` >&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 "initramfs-ostree-${version}.img" "initramfs-ostree-${alt_version}.img"; do
    if test -e "${dirname}/${i}" ; then
      initrd="$i"
      ostree_linux_entry "GNOMEOS 3.4" "${version}" \
	        "${GRUB_CMDLINE_LINUX}" "${GRUB_CMDLINE_LINUX_DEFAULT}"
      break
    fi
  done

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