#!/bin/sh
# /usr/sbin/bootcdmkinitrd

set -u

KERN=$(uname -r)
INITRD=/boot/initrd.img-$KERN
ETCMKI=/etc/mkinitrd

# Warning

echo "Warning: this script assumes the following:"
echo "- the running kernel is the one that will be used on bootcd"
echo "- initrd is used"
echo "- lilo is used"
echo "Warning: this script will do the following:"
echo "- /etc/mkinitrd/ will be changed." 
echo "- mkinitrd will be called. This will change $INITRD."
echo "- lilo will be called."
while :; do
  echo -n "OK to continue ? (y|n)"
  read A
  [ "$A" = "n" ] && exit
  [ "$A" = "y" ] && break
done

# Checks

if [ ! "$(grep "^[[:blank:]]*initrd=" /etc/lilo.conf)" ]; then 
  echo "/etc/lilo.conf has no line initrd=. This means that you" >&2
  echo "are not using lilo, or that you are not using initrd." >&2
  echo "This skript only works with lilo and initrd." >&2
  exit 1
fi

if [ ! "$(grep "^[[:blank:]]*initrd=/initrd.img[[:blank:]]*$" /etc/lilo.conf)" ]; then 
  echo "Your /etc/lilo.conf has no line with initrd=/initrd.img. Because" >&2
  echo "this script can only support standard configurations, please edit" >&2
  echo "lilo.conf run lilo and reboot to test your configuration. Then " >&2
  echo "run this script again." >&2
  exit 1
fi

# Check for file equality: /initrd.img could be a link to
# /boot/initrd.img-$(uname -r) or a link to boot/initrd.img-$(uname -r)
cmp -s /initrd.img $INITRD
if [ $? -ne 0 ] || [ ! -L /initrd.img ]; then
  echo "/initrd.img must be a link to $INITRD." >&2
  exit 1
fi

if [ ! -d $ETCMKI ]; then
  echo "ERROR: No mkinitrd config dir $ETCMKI." >&2
  echo "       Is initrd-tools.deb installed ?" >&2
  exit 1
fi

if [ ! -f $INITRD ]; then
  echo "$INITRD does not exist." >&2
  exit 1
fi



# Start

[ -f /etc/mkinitrd.tgz ] && mv /etc/mkinitrd.tgz /etc/mkinitrd.tgz.old
(cd /etc; tar czf mkinitrd.tgz mkinitrd)

F=/etc/mkinitrd/exe
touch $F
cp $F $F.tmp
cat $F.tmp | grep -v "^/sbin/discover\>" >$F
echo "/sbin/discover" >>$F
rm $F.tmp

F=/etc/mkinitrd/modules
touch $F
cp $F $F.tmp
awk ' 
	!/^cdrom$/ &&
	!/^isofs$/ {
		print
	}
' < $F.tmp >$F
echo "cdrom" >>$F
echo "isofs" >>$F
rm $F.tmp

F=/etc/mkinitrd/files
touch $F
cp $F $F.tmp
awk '
	!/^\/usr\/share\/discover\/.*\.lst$/ &&
	!/^\/lib\/modules\/.*\/kernel\/drivers\/cdrom\/cdrom\.o$/ {
		print
	}
' < $F.tmp >$F
ls /usr/share/discover/*.lst >>$F
ls /lib/modules/$KERN/kernel/drivers/cdrom/cdrom.o >>$F
rm $F.tmp

F1=/etc/mkinitrd/scripts/50bootcddiscover
cat <<end1 >$F1
#!/bin/sh
F2=\$INITRDDIR/scripts/bootcd
cat <<end2 >\$F2
/bin/echo "running /scripts/bootcd" >&2
mount -nt proc proc /proc
MODULES=\\\$(discover --disable-all --enable=pci --module scsi)
for M in \\\$MODULES; do
  modprobe \\\$M
done
umount -n /proc
end2
chmod 755 \$F2
end1
chmod 755 $F1

mkinitrd -k -o /initrd.img
lilo

# Warning

echo "Please reboot now, before using bootcdwrite"
