#!/bin/sh

LIBS="libc libcom_err libe2p libnss_compat"
ZLIBS="libext2fs.so libnsl libnss_files libuuid"
BINS="gzip ls mke2fs ash open fdisk badblocks rm chmod"
# chmod could be a VIRTBIN, but the runinstall2 script uses it to set things up
VIRTBINS="cat lsmod mkdir mknod mount rm umount"  
ZBINS="insmod install2"

PCMCIA_SBINS="cardmgr"
MODLINKS="block cdrom misc net scsi"

export PATH=$PATH:/sbin:/usr/sbin

usage () {
    echo "updsupp: <imagetree> <kernel-version>" 2>&1
    exit 1
}

if [ -z "$1" -o -z "$2" ]; then
    usage
fi

if [ ! -d "$1/misc/src/install" ]; then
    echo "$1 is not a valid directory" 2>&1
    usage
fi

if [ ! -d "/lib/modules/$2/pcmcia" ]; then
    echo "$2 is not a valid modules directory" 2>&1
    usage
fi

PATH=$1/misc/src/install:/usr/sbin:/usr/bin:/bin:/sbin

rm -rf supp/lib/*
ln -s /tmp supp/lib/modules

cp -a /lib/ld-2*.so supp/lib
cp -a /lib/ld-linux.so.2* supp/lib

for n in $LIBS $ZLIBS; do
	# this preserves hard links
	(cd /lib; tar cSpf - ${n}[-.]*) | (cd supp/lib; tar xSpf -)
done

(cd supp/lib; file * | grep 'shared object' | cut -d: -f1 | xargs strip)

cd supp/lib
for n in $ZLIBS; do
    for file in ${n}*; do
	if [ -f $file -a ! -L $file ]; then
	    gzip -9 $file
	    ln -s /tmp/$file .
	fi
    done
done
cd ../..

for n in $BINS; do
	rm -f supp/usr/bin/$n
	cp -af `which $n` supp/usr/bin
done

for n in $VIRTBINS; do
	ln -sf /sbin/install2 supp/usr/bin/$n
done

for n in $ZBINS; do
	rm -f supp/usr/bin/$n
	strip `which $n`
	gzip -9 < `which $n` > supp/usr/bin/$n
	chmod 755 supp/usr/bin/$n
done

rm -rf pcmcia/lib/modules
mkdir pcmcia/lib/modules
mkdir pcmcia/lib/modules/$2
mkdir pcmcia/lib/modules/$2/pcmcia

cp /lib/modules/$2/pcmcia/* pcmcia/lib/modules/$2/pcmcia

# unfotunately, this breaks things
# strip --strip-unneeded pcmcia/lib/modules/$2/pcmcia/*.o

for n in $MODLINKS; do 
	ln -s /modules pcmcia/lib/modules/$2/$n
done

for n in $PCMCIA_SBINS; do
	rm -f pcmcia/sbin/$n
	cp -af /sbin/$n pcmcia/sbin/$n
done

rm supp/pcmcia.cgz
(cd pcmcia; find . -type f -o -type l | cpio -H crc -o) | gzip -9 > supp/pcmcia.cgz