#!/bin/sh
# mkSETUP 
# Install SETUP

if [ -z "$SETUP" ] || [ -z "$SETUP_DEV" ] || 
   [ -z "$TARGET" ] || [ -z "$RELEASE_ISOLINUX" ]; then
   echo "Missing configuration"
   exit 1
fi


cat << EOF
Making SETUP partition for testing.

This operation will:
- format $SETUP_DEV,
- install the content of $RELEASE_ISOLINUX/initrd.img
- copy kernel from $TARGET
- set necessary init script.

Press <enter> to continue of Ctrl-Break to abort.
EOF

read pause

mk_rcs()
{

cat <<EOF > $SETUP/etc/init.d/rcS
#!/bin/sh

PATH=/sbin:/bin:/usr/bin:/usr/sbin:/usr/local/bin

# Mount proc fs
mount none /proc -t proc

# remount read-write
mount -w -v -n -o remount /

# Delete dirty files
rm -f /etc/mtab

# Remounting the partitions will initialize the new /etc/mtab:
mount -a

# Clearing other stuff
rm -f /tmp/*
rm -f /etc/forcefsck /etc/fastboot /etc/nologin /etc/shutdownpid
rm -f /var/run/utmp /var/run/*.pid /var/run/lpd* /var/run/ppp* 
rm -f /var/lock/* /var/spool/uucp/LCK..* /var/log/setup/tmp/*

# Make sure the permission
chmod 755 /
chmod 1777 /tmp /var/tmp

## Create basic things
mkdir -p /var/log/lastlog
touch /var/run/utmp
chown root.utmp /var/run/utmp
chmod 664 /var/run/utmp

################################################################
# Start the setup
# Show our splash screen
if [ -x /etc/issue ]; then
  /etc/issue
fi

# lets start the setup program.
/sbin/setup

EOF

}

mk_fstab()
{
cat <<EOF > $SETUP/etc/fstab

$SETUP_DEV   /      auto   defaults   1  1
none         /proc  proc   defaults   0  0

EOF
}

mk_lilo()
{
cat <<EOF >> /etc/lilo.conf
## SETUP
## You must mount $SETUP_DEV under $SETUP
image = $SETUP/boot/vmlinuz
    root = $SETUP_DEV
    label = VLSETUP
    read-only
    vga = normal
EOF
}


## Mount the SETUP
umount $SETUP &>/dev/null
mke2fs $SETUP_DEV
mkdir -p $SETUP
mount -v $SETUP_DEV $SETUP || exit 1

## Mount the TARGET
if ! mount | grep -qe "on *$TARGET "; then
   mkdir -p $TARGET
   mount -v $TARGET_DEV $TARGET || exit 1
fi

## mount initrd from iso-skel
INITRD=tmp/initrd
LOOP=setup
mkdir -p $INITRD/$LOOP
cp $RELEASE_ISOLINUX/initrd.img $INITRD/initrd.gz || exit 1
(
cd $INITRD
gunzip initrd.gz
mount -v -o loop initrd $LOOP || exit 1
## Copy anything from initrd to SETUP
rm -rf $SETUP/*
cp -au $LOOP/* $SETUP
umount $LOOP
rm initrd
)

## Copy kernel to the SETUP
echo Copying kernel from TARGET to the SETUP
mkdir -p $SETUP/boot
(
cd $SETUP/boot
for ll in vmlinuz System.map config; do
   ff=`readlink $TARGET/boot/$ll`
   echo Copying $ff
   cp -au $TARGET/boot/$ff .
   if [ $? != 0 ]; then
	echo ERROR: Cannot copy $ll
	exit 1 
   fi
   rm -f $ll
   ln -sf $ff $ll
   done
)

echo Making rcS
mk_rcs

echo Making fstab
mk_fstab

echo Configuring LILO
if ! grep -e "^ *root *= *$SETUP_DEV" /etc/lilo.conf; then
    mk_lilo
fi

echo Done. You may boot $SETUP_DEV for testing now.
echo Please examine the /etc/lilo.conf
echo call lilo -v
echo then reboot 

