#!/bin/bash
#
# Copyright (c) 2006 Gawain Lynch <gawain DOT lynch AT gmail DOT com>
# License: GPL v2 (http://www.gnu.org/licenses/gpl.html)

# Variables
TMPDIR=`mktemp`
BASEARCH="i586"
INITRD=$1
KERNEL=$2
MODULE="ipw2200"
FIRMWARE="ipw2200-bss.fw"
MODINFO="/sbin/modinfo"

help() {
echo "Usage: " `basename $0` "[INITRD] [KERNEL_RPM] [OUTPUT_DIR]"
echo ""
echo "	INITRD 		- initrd from isolinux/ directory in install tree"
echo "	KERNEL_RPM 	- Matching kernel RPM, usually the $BASEARCH kernel"
echo "			  found in Fedora/RPMS/ directory in the install tree"
echo "  OUTPUT_DIR	- (Optional) Directory to output modified initrd, else"
echo "			  current directory is used"
echo ""
}

[ $# -lt 2 ] && help && exit 1
[ $1 = "" ] && help && exit 1
[ $2 = "" ] && help && exit 1
[ $# -eq 3 ] && OUTDIR=$3 || OUTDIR=`pwd`

# Do some work eh...
pushd $TMPDIR > /dev/null

# Get the kernel version
KERNELVER=`rpm -qp $KERNEL | sed 's/kernel-//'`
[ $? -ne 0 ] && echo "Does not look like a valid RPM file" && exit 1

# Make the directories to hold bits
mkdir kernel
mkdir initrd
mkdir modules

# Unpack the kernel
cd $TMPDIR/kernel
rpm2cpio $KERNEL | cpio -i --make

# Unpack the initrd
cd $TMPDIR/initrd
gzip -dc < $INITRD | cpio -id

# Unpack the modules
cd $TMPDIR/modules
gzip -dc $TMPDIR/initrd/modules/modules.cgz | cpio -id
MODDIR=`find . -type d | grep i586`

# Copy the module over
cd $TMPDIR
cp `find kernel -name $MODULE.ko` modules/$KERNELVER/$BASEARCH/

# Copy in module dependancies
for mod in `$MODINFO modules/$KERNELVER/$BASEARCH/$MODULE.ko | grep depends | awk '{print $2}'`; do
	cp `find kernel/lib/modules/$KERNELVER -name $mod.ko` modules/$KERNELVER/$BASEARCH/
done

# Add PCI aliases to modules.alias
cd $TMPDIR
echo "alias net-pf-10 ipv6" > $TMPDIR/modules.alias.tmp

$MODINFO $TMPDIR/modules/$KERNELVER/$BASEARCH/$MODULE.ko | grep alias | \
	awk -v mod="$MODULE" '{ print "alias " $2 " " mod}' | sort >> $TMPDIR/modules.alias.tmp

cat $TMPDIR/initrd/modules/modules.alias | grep -v "alias net-pf-10 ipv6" >> $TMPDIR/modules.alias.tmp
cat $TMPDIR/modules.alias.tmp > $TMPDIR/initrd/modules/modules.alias

# Add entry to module-info
echo $MODULE >> $TMPDIR/initrd/modules/module-info
echo "	eth" >> $TMPDIR/initrd/modules/module-info
echo "	\"" `$MODINFO modules/$KERNELVER/$BASEARCH/$MODULE.ko | grep description | sed 's/description:    //'` "\"" \
	>> $TMPDIR/initrd/modules/module-info

# Copy the firmware in
cd $TMPDIR
mkdir -p initrd/lib/firmware/
cp /lib/firmware/$FIRMWARE initrd/lib/firmware/

# Make new modules.cgz
cd $TMPDIR/modules
find . | cpio -o -H crc | gzip -c9 > $TMPDIR/initrd/modules/modules.cgz

# Make new initrd
cd $TMPDIR/initrd
find . | cpio -o -c | gzip -9 > $OUTDIR/`basename $INITRD`

# Clean up
popd > /dev/null
[ "$TMPDIR" != "/" ] && rm -rf $TMPDIR
