#!/bin/bash
# $Id: make_initrd,v 1.4 2008-09-21 15:05:51 tim Exp $

#ROOTPATH=`pwd`/${1}-root
ROOTPATH=/mnt/otherboot

rm -fr initrd/bin
rm -fr initrd/dev
rm -fr initrd/etc
rm -fr initrd/lib
rm -fr initrd/newroot
rm -fr initrd/proc
rm -fr initrd/sbin
rm -fr initrd/usr

LANG=C
kernelver=$( ls -l ${ROOTPATH}/vmlinuz | awk '{print $11}' | sed "s/^.*vmlinuz-//" )
echo $kernelver

(
    makepath()
    {
	if [ -d $1 ]; then
	    return 0
	fi
	makepath $( dirname $1 )
	mkdir $1
    }
    copyfile()
    {
	makepath ./$( dirname $1 )
	cp -p ${ROOTPATH}$1 ./$1
    }
    copymodule()
    {
	if [ -f ${ROOTPATH}$1 -a ! -f ./$1 ]; then
	    copyfile $1
	fi
    }

    cd initrd
    (
	IFS="="
	grep "^setCmd.*=" linuxrc |
	    while read -r a b; do
		copyfile $b
	    done
    )

    for i in /bin/dash; do
	copyfile $i
    done

    rm -f bin/sh
    ln -s dash bin/sh

    EXECS='*bin/* usr/*bin/*'

    for i in `
	    for j in $EXECS; do 
		ldd $j 
	    done | 
		awk '{print $3}' | sort -u`; do
	makepath ./$( dirname $i )
	cp -p ${ROOTPATH}$i ./$i
    done

    for i in dev etc newroot proc; do
	if [ ! -d $i ]; then
	    mkdir $i
	fi
    done
    
    rm -f etc/modules.conf
    touch etc/modules.conf

    rm -f etc/mtab
    ln -s /proc/mounts etc/mtab

    rm -f etc/ld.so.cache
    cp /sbin/ldconfig sbin
    chroot . /sbin/ldconfig
    rm sbin/ldconfig

    for i in $( cat ../modules.lst ); do
	copymodule /lib/modules/${kernelver}/$i
	for j in $( cat ${ROOTPATH}/lib/modules/2.4.27-2-386/modules.dep | 
		while read a; do echo $a; done |
		grep "^/lib/modules/${kernelver}/$i:" ); do
	    copymodule $j
	done
    done

    for i in console null; do
	cp -dpR ${ROOTPATH}/dev/$i dev/$i
    done

    for i in cciss ide mapper md scsi; do
	ln -s /newroot/devfs/$i dev/$i
    done
)

rm -f initrd.cramfs
depmod -a -F ${ROOTPATH}/boot/System.map-${kernelver} -C initrd/etc/modules.conf -b initrd ${kernelver}
mkcramfs initrd initrd.cramfs

exit 0

