#!/bin/bash

#Written On: Dec 2014
#Written By: Tal
#Written For: Ubuntu Forums Community
#Description:
#	This script makes sure that any kernels that the original OS can't
#	run will not be picked up by /etc/grub.d/10_linux by moving them
#	to /boot/rs_kernels/
#	This script also deletes any kernels in /boot/rs_kernels/ that
#	the original OS also supports, since that means a recent update
#	to the original OS just installed the same kernel files to
#	/boot. After this happens, 06_RAMSESS will find the kernel in
#	/boot/ and fix the grub menu automatically

#If /boot/orig doesn't exist, there's nothing for us to do
if [[ ! -e /boot/orig ]]
then
	echo "/boot/orig not found. Exiting zc_sort_kernels"
	exit 0
fi

#If /boot/ram_sess doesn't exist, there's nothing for us to do
if [[ ! -e /boot/ram_sess ]]
then
	echo "/boot/ram_sess not found. Exiting zc_sort_kernels"
	exit 0
fi

#Create folder if it doesn't exist
if [[ ! -d /boot/rs_kernels ]]
then
	sudo mkdir /boot/rs_kernels/
fi

#If there are any kernels in /boot/ that the original OS doesn't support,
#move them to /boot/rs_kernels/
for KERNEL_FILE in $(ls -1 /boot/vmlinuz-* /vmlinuz-* 2>/dev/null)
do
	KERNEL_VERSION=$(basename $KERNEL_FILE | sed 's/vmlinuz-//g')

	if ! grep -qx $KERNEL_VERSION /boot/orig
	then
		echo "Moving $KERNEL_VERSION to /boot/rs_kernels/"
		mv -v /boot/vmlinuz-$KERNEL_VERSION* /boot/rs_kernels/
		mv -v /boot/initrd*-$KERNEL_VERSION* /boot/rs_kernels/
	fi
done

#If there are any kernels in /boot/rs_kernels/ that the original OS also
#supports, than we now have duplicate files in /boot and
#/boot/rs_kernels/, so delete the ones from /boot/rs_kernels/
for KERNEL_FILE in $(ls -1 /boot/rs_kernels/vmlinuz-* 2>/dev/null)
do
	KERNEL_VERSION=$(basename $KERNEL_FILE | sed 's/vmlinuz-//g')

	if grep -qx $KERNEL_VERSION /boot/orig
	then
		echo "Deleting $KERNEL_VERSION from /boot/rs_kernels/"
		rm -v /boot/rs_kernels/*$KERNEL_VERSION*
	fi
done
