#!/bin/bash
#
# cmdinitrd - use command on contents of an initrd image
#
# Copyright (C) 2012 SuSE Linux Products GmbH, Nuernberg, Germany
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# This file is kept in the following git repository:
#
# https://github.com/openSUSE/mkinitrd.git
#

usage() {
    echo "Usage: cmdinitrd <initrd> <cmd> [<opt>] <file> [<local>]"
}

initrd="${1}"
infile=
typeset -a argv=()
typeset -i argc=0
shift

while [ "$1" ] ; do
    case $1 in
        -*)
	    argv[$argc]="$1"
	    let argc++;
	    shift
	    ;;
	*)  if ((argc == 0)) ; then
		    argv[0]="$1"
		    let argc++;
		    shift
	    else
		    infile="$1"
		    shift
		    break
	    fi
    esac
done

if [ -z "$initrd" ] ; then
    echo "No initrd file specified"
    usage
    exit 1
fi

if [ ! -e "$initrd" ] ; then
    echo "No initrd file \`$initrd' found"
    usage
    exit 1
fi

if [ -z "$infile" ] ; then
    echo "No file of the initrd image specified"
    usage
    exit 1
fi

if ! type -p ${argv[0]} &> /dev/null ; then
    echo "No command \`${argv[0]}' found"
    usage
    exit 1
fi

uncomp()
{
	local uncompress="gzip"
	case $(file -bL "$1") in
	gzip\ *)    uncompress="gzip"	;;
	bzip2\ *)   uncompress="bzip2"	;;
	LZMA\ *)    uncompress="lzma"	;;
	XZ\ *)	    uncompress="xz"	;;
	esac
	command $uncompress -cdfq < "$1"
}

case "${argv[0]##*/}" in
    diff)   test -n "$1" || set -- $infile ;;
esac

uncomp "$initrd" | exec cpio --quiet -i --to-stdout "${infile#/}" | exec ${argv[@]} - ${1+"$@"}
