#!/bin/bash
# Scan vmlinuz and detect fs 
# Inspired by mindi
# 20130429

Die(){
echo $1
exit -1
}

detection(){
echo -e "--- Kernel fs detection routine\n"
# local constants (filesystem magic strings)
local lcMagicCramfs="<3>cramfs: wrong magic"
local lcMagicExt2fs="EXT2-fs: blocksize too small for device."
local lcMagicExt3fs="<3>EXT3-fs: blocksize too small for journal device."
local lcMagicInitfs="<6>checking if image is initramfs...|<6>Unpacking initramfs...|<6>Trying to unpack rootfs image as initramfs"

echo "`cat /etc/*release`"
lvKernelImage=/boot/vmlinuz-`uname -r`
echo -e "Kernel is $lvKernelImage\n"

	# verify that file exists
	[ ! -f $lvKernelImage ] && Die "File $lvKernelImage not found. Terminating."

	# Kernel may be gzip compressed
	file $lvKernelImage 2>&1 | grep -q gzip
	if [ $? -eq 0 ]; then
		lvScanRes=`gzip -cd $lvKernelImage | strings | grep -E "$lcMagicCramfs|$lcMagicExt2fs|$lcMagicExt3fs|$lcMagicInitfs"`
		echo -e "\n$lvKernelImage is a gzipped file\n"
	else
		echo -e "\n$lvKernelImage is not a gzipped file"
		echo "`file $lvKernelImage`"
		echo -e "Scan $lvKernelImage for gzip embedded and initrd filessystem support\n"
		# get offet of gzip magic "1f8b0800" in file
		lvOffset=`od -vA n -t x1 $lvKernelImage | tr -d '[:space:]' | awk '{ print match($0, "1f8b0800")}'`
		[ $lvOffset -eq 0 ] && Die "gzip magic not found in file $lvKernelImage. Terminating."
		lvOffset=`expr $lvOffset / 2`
		echo "  GetInitrdFilesystemToUse(): gzip magic found at lvOffset $lvOffset."

		# scan kernel image for initrd filessystem support
		lvScanRes=`dd ibs=1 skip=$lvOffset if=$lvKernelImage obs=1M 2>/dev/null | gunzip -c 2> /dev/null | strings | grep -E "$lcMagicCramfs|$lcMagicExt2fs|$lcMagicExt3fs|$lcMagicInitfs"`
	fi
	echo -e "\nHere are the fs detected :"
	echo -e "lvScanRes=$lvScanRes\n"

	# determine which filesystem to use for initrd image: ext2fs, gzip'ed cpio (initramfs ) or cramfs
	if [ `echo $lvScanRes | grep -Ec "$lcMagicExt2fs"` -eq 1 ]; then
		lvUseFilesystem="ext2fs"
	elif [ `echo $lvScanRes | grep -Ec "$lcMagicExt3fs"` -eq 1 ]; then
		lvUseFilesystem="ext3fs"
	elif [ `echo $lvScanRes | grep -Ec "$lcMagicInitfs"` -eq 1 ]; then
		lvUseFilesystem="initramfs"
	elif [ `echo $lvScanRes | grep -Ec "$lcMagicCramfs"` -eq 1 ]; then
		lvUseFilesystem="cramfs"
	else
		# In that case, we are after 2.6.30 and use the supported initramfs 
		echo "In that case, we are after 2.6.30 and use the supported initramfs"
		lvUseFilesystem="initramfs"
	fi
	echo -e "lvUseFilesystem=$lvUseFilesystem\n"
}

echo -e "--- Main"
detection
