#!/bin/bash
#
# cs_show_initrd
#
# (c) 2011-2017 SUSE Linux GmbH, Germany.
# (c) 2018-2019 SUSE LLC
# Author: L.Pinne.
# GNU General Public License v2. No warranty.
# http://www.gnu.org/licenses/gpl.html
#
# Version: 2019-12-05
#

EXE="$0"
#CFG="/etc/ClusterTools2/cs_show_initrd"
#test -s $CFG && source $CFG


function help() {
	echo "usage:	$(basename "$EXE")"
	echo "	$(basename "$EXE") [OPTION]"
	echo
	echo " --help		show help"
	echo " --version	show version"
	echo " --all		list all initrd files"
	echo " --etc		list initrd etc files"
	echo " --modules	list initrd modules"
#	echo " --compare	compare initrd modules with /etc/sysconfig/kernel"
	echo
}


function show_initrd() {
	#file $1 | awk '$2=="gzip"' >/dev/null &&\
	#	/usr/bin/zcat $1 | cpio -it 2>/dev/null
	# TODO verbose, e.g.: cpio -itv 2>/dev/null | colrm 43 54
	file "$1" | awk '$2=="XZ"' >/dev/null &&\
		/usr/bin/xz --decompress --stdout "$1" | cpio -it 2>/dev/null
}


function list_modules() {
	INITRDMODS=$(show_initrd "$1" | grep "lib/modules.*.ko" |\
		while read -r; do
			basename "$REPLY" .ko
		done | sort
	)
}


# main()
case $1 in
	 -v|--version)
		echo -n "$(basename "$EXE") "
		head -11 "$EXE" | grep "^# Version: "
		exit
	;;
	-h|--help)
		help
		exit
	;;
	-m|--modules)
		for f in /boot/initrd /boot/initrd-xen; do
			echo $f:
			if [ -f $f ]; then
				show_initrd $f | grep "lib/modules.*.ko"
			else
				echo "... skipping"
			fi
			echo
		done
	;;
	-e|--etc)
		for f in /boot/initrd /boot/initrd-xen; do
			echo $f:
			if [ -f $f ]; then
				show_initrd $f | grep "etc/"
			else
				echo "...skipping"
			fi
			echo
		done
	;;
	# TODO compare etc file from initrd with systems etc
	# TODO calculate md5sum for initrd file list, like cs_sum_base_config
	-c|--compare)
		# TODO SLES12 /etc/dracut.donf.d/*.conf
		# TODO put this into fucntion
		SYSCONFMODS=$(awk -F"=" '$1=="INITRD_MODULES"{print $2}' /etc/sysconfig/kernel |\
				 tr -d \" | tr " " "\n" | sort)
		f="/boot/initrd"
		list_modules $f
		for m in $SYSCONFMODS; do
			echo "$INITRDMODS" | grep -q "$m"
			test $? -eq 0 && echo "OK $f $m"
			test $? -ne 0 && echo "NO $f $m"
		done
		
		SYSCONFMODS=$(awk -F"=" '$1=="DOMU_INITRD_MODULES"{print $2}' /etc/sysconfig/kernel |\
				 tr -d \" | tr " " "\n" | sort)
		f="/boot/initrd-xen"
		list_modules $f
		for m in $SYSCONFMODS; do
			echo "$INITRDMODS" | grep -q "$m"
			test $? -eq 0 && echo "OK $f $m"
			test $? -ne 0 && echo "NO $f $m"
		done
	;;
	*)
		for f in /boot/initrd /boot/initrd-xen; do
			echo $f:
			if [ -f $f ]; then
				show_initrd $f
			else
				echo "... skipping"
			fi
			echo
		done
	exit
esac
#
