#!/bin/sh

LIBS="libc libext2fs.so libuuid libnss_files libe2p libtermcap libcom_err
      libnsl libnss_files libnss_dns libproc"
USRLIBS=""
BINS="bzip2 ls mke2fs bash open fdisk badblocks rm chmod cat lsmod
      mkdir mknod mount rm umount ln cpio rpm vi tar cp ifconfig route
      e2fsck grep sed gzip dd cpio mt mv ping traceroute sync chroot restore
      head tail swapon rpm ps tac pico vim df"
DEVS="hda hdb hdc hdd sda sdb sdc sde sdf sdg scd tty1 tty2 console ram null 
      systty zero"
USRLIB="rpmrc rpmpopt"
ETC="services protocols"

usage () {
    echo "updrescue takes no parameters" 2>&1
    exit 1
}

if [ -n "$1" ]; then
    usage
fi

rm -rf rescue
mkdir -p rescue/lib 		rescue/usr 		rescue/bin 	\
	 rescue/etc 		rescue/usr/lib 		rescue/mnt 	\
	 rescue/mnt/image	rescue/dev 		rescue/tmp 	\
	 rescue/mnt/floppy	rescue/mkdir		rescue/proc
ln -s bin rescue/sbin
ln -s ../bin rescue/usr/bin
ln -s ../bin rescue/usr/sbin
ln -s gzip rescue/bin/gunzip
ln -s swapon rescue/bin/swapoff
ln -s bash rescue/bin/sh

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


for n in $ETC; do
	cp -a /etc/$n rescue/etc
done

echo "Copying libraries"

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

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

echo "Stripping libraries"
(cd rescue/lib; file * | grep 'shared object' | cut -d: -f1 | xargs strip)

echo "Copying binaries"

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

echo "Copying devices"

for n in $DEVS; do
	for d in /dev/${n}*; do
	    cp -af $d rescue/dev
	done
done

for n in $USRLIB; do
	cp -af /usr/lib/$n rescue/usr/lib
done

cat >> rescue/etc/fstab <<EOF
/dev/ram	/		ext2	defaults
/proc		/proc		proc	defaults
/dev/fd0	/mnt/floppy	ext2	defaults
EOF

touch rescue/etc/mtab

cat >> rescue/sbin/init <<EOF
#!/bin/sh

mount -n -o remount,rw /
mount /proc
cp /proc/mounts /etc/mtab

open -l /bin/sh

echo ''
echo 'This is the Red Hat rescue disk. Most of the basic system commands are'
echo 'in /bin.'
echo ''
echo 'Type exit to halt the system.'
echo ''

/bin/sh

echo "Unmounting filesystems..."
tac /proc/mounts | while read line ; do
    set $line
    if [ $2 != "/" ]; then
	umount $1
    fi
done
echo "Halting system.. All fixed? :-)"
EOF

chmod +x rescue/sbin/init

mkdir -p rescue/usr/share/terminfo/l
cp /usr/share/terminfo/l/linux rescue/usr/share/terminfo/l

infocmp linux > foo
infotocap -C foo > rescue/etc/termcap
rm -f foo
