#!/bin/sh -efu

# initrddiff
#    Perform a diff on the files contained within different initrd
#    images and show the result.

# Usage: initrddiff [diffoptions] <from_image> <to_image>
#
# diffoptions:
#    Most of the single letter options allowable by GNU diff(1) are acceptable.
#    By default -NrU0 is used. If providing a value don't forget the -r option.
#
# License: GPL

. shell-error

[ -z "${DEBUG-}" ] || set -x

decompress() {
	local cmd='cat' typ=
	typ="$(file -b "$1")"
	case "$typ" in
		'bzip2 compressed data'*) cmd='bunzip -c' ;;
		'gzip compressed data'*)  cmd='gunzip -c' ;;
		'xz compressed data'*)    cmd='unxz -c'   ;;
	esac
	$cmd "$1"
}

extract() {
	decompress "$1" |
		cpio -t |
		sed -e "s,lib/modules/[^/]\+,lib/modules/<version>," |
		sort
}

diffopts=
while [ "$#" -gt 2 ]; do
	diffopts="$diffopts $1"
	shift
done

if [ $# != 2 ]; then
	printf '%s\n' "Usage: $PROG [diffoptions] <from-image> <to-image>"
	exit
fi

for f; do
	[ -f "$f" ] ||
		fatal "No such file or directory"
done

exec 3<<EOF
`extract "$1"`
EOF
exec 4<<EOF
`extract "$2"`
EOF

diff ${diffopts:--NrU0} /dev/fd/3 /dev/fd/4 |
	sed \
		-e "s,/dev/fd/3,${1##*/}," \
		-e "s,/dev/fd/4,${2##*/},"
