#!/sbin/perl

sub flush {
    local($old) = select(shift);
    $| = 1;
    print "";
    $| = 0;
    select($old);
}

$ENV{'PATH'} = "/usr/X11/bin:/bin:/usr/bin:/sbin:/usr/sbin";
$ENV{'LD_LIBRARY_PATH'} = "/lib:/usr/lib:/usr/X11/lib";

# Run bdflush.
system 'update';

# Remount /
system 'mount -n -o remount,rw /';

# Mount /proc
system 'mount -t proc /proc /proc';

# Clean out /etc.
unlink '/etc/mtab~', '/etc/fastboot', '/etc/nologin';
open(FD,'>/etc/utmp');
open(FD,'>/etc/mtab');
close FD;

# Enter root into mtab.
system 'mount -f /';

# Set the system clock. (Assume GMT for now...)
#system 'clock -u -s';

$ENV{'PATH'} = "/bin:/usr/bin:/sbin:/usr/sbin:/mnt2/bin:/mnt2/usr/bin:/mnt2/sbin:/mnt2/usr/sbin:/mnt3/bin:/mnt2/mnt/cdrom/bin";

# Start a shell in another VT
system 'open /bin/ash';

$ENV{'PATH'} = "/bin:/usr/bin:/sbin:/usr/sbin";
$ENV{'TERM'} = "linux";

# Create space for a second ramdisk
open(VERSION, "</proc/version") || die("cannot open /proc/version");
$_ = <VERSION>;
chop;
close(VERSION);

($release) = /version ([0-9\.]+) /;
$release =~ s/\.[0-9]+$//;
system "insmod /lib/ramdisk-$release.o";

print "RHL: Insert ramdisk 2 floppy and press ENTER";
flush(STDOUT);
$line = <>;
#print "\nLoading... This will take a minute or two...\n";
#system 'exec dd if=/dev/fd0 of=/dev/ram2 bs=64k';

open(DISK, "</dev/fd0") || die("couldn't open /dev/fd0");
open(RAM, ">/dev/ram2") || die("couldn't open /dev/ram2");

print "RAMDISK2: Loading 1440 blocks into RAM disk";

$nblocks = 1440;
while ($nblocks) {
    $amount = ($nblocks > 16) ? 16 : $nblocks;
    $nblocks -= $amount;

    read(DISK, $buffer, 1024 * $amount) || die("couldn't read $amount blocks");
    syswrite(RAM, $buffer, 1024 * $amount) || die("couldn't syswrite $amount blocks");
    print ".";
    flush(STDOUT);
}
close(DISK);
close(RAM);
print "\ndone\n";

system 'mount -t ext2 /dev/ram2 /ramdisk';

# Turn off screen blanking
# system 'setterm -blank 0 -powersave off';

# Let's free up some tmp space by erasing old binaries
unlink('/sbin/setterm');
`/ramdisk/bin/rm /lib/ramdisk*.o`;
unlink('/sbin/uname');

unlink('/bin');
symlink('/ramdisk/bin', '/bin');

#rmdir('/tmp');
#symlink('/ramdisk/tmp', '/tmp');

system 'syslogd > /dev/null 2>&1';
system 'klogd > /dev/null 2>&1';

# Run the install script.
if ( ! ($child = fork)) {
    $ENV{'PERLLIB'} = "/usr/lib/perl";
    exec '/usr/lib/perl/install';
}

$pid = 0;

while ( (( $pid = wait ) != -1) && $pid != $child) { }

# Reboot the system.
exec '/sbin/shutdown';
