#!/usr/bin/perl
# $Id: grub-ins.pl,v 1.3 2000/01/31 15:02:59 duwe Exp $

$nam = $insimage = $ARGV[0];
$nam =~ s/\.//g;

open (BGML, "</boot/grub/menu.lst") || die;

# Determine if this is a true Pentium or better and we can use that kernel,
# and if we need to disable SMP (for AMD, Cyrix, ...). Set failsafe defaults.
$apic = " noapic nosmp";
$pc97 = "";
if (open(CI, "</proc/cpuinfo")) {
  while(<CI>) {
    m/^\s*flags\s*:.* fpu\b.* tsc\b/ && ($pc97 = "-pc97");
    m/^\s*flags\s*:.* apic\b/ && ($apic = "");
  }
  close CI;
}

# Now let's see whether we need an initrd for the current root.
$thisroot = `/usr/sbin/rdev`;
$thisroot =~ s/\s.*$//sm;
$initrd = "\ninitrd = /boot/initrd-$insimage.gz\n";
($thisroot =~ m,^/dev/hd, ) && ( $initrd = "" );

$secret = "no";
$otherimg = "";
# Write it out just before the first "title=" entry (if there is one)
while (<BGML>) {
  if (m/^\s*password\s*=/i) { $secret = "yes"; }
  s/^\s*title\s*=\s*oldlinux\b/title = Linux-cruft$$/i; # the best we can do
  s/^\s*title\s*=\s*linux\b/title = OldLinux/i;
  if (m/^\s*title\s*=/) { $otherimg = $_; last; }
  print;
}

$vga = "";
if (open(ESC, "</etc/system.cnf")) {
  while(<ESC>) {
    m/^\s*CONF_GRAPHIC_CARD1_VESAMODE\s*=\s*(\w+)/ && ($vga = "$1");
  }
  close ESC;
}
$vga = "274" if ($vga eq "");

# try to figure out the boot partition ("slice").
if (open(FSTAB, "</etc/fstab")) {
  while(<FSTAB>) {
    m,^\s*(/dev/[\S]+)\s*/boot\s, && ($bootslice = $1);
  }
  close FSTAB;
}
$bootslice = $thisroot unless $bootslice;
$bootslice =~ s,\s*(/dev/.d.),,;
$bootdisk  = $1;		# what we just cut off: device w/o partition
$bootslice = $bootslice - 1;

$biosdisk = "hd0";		# default: first disk
if (open(DEVMAP, "</boot/grub/device.map")) {
  while(<DEVMAP>) {
    m,^\s*\((\w+)\)\s*$bootdisk, && ($biosdisk = $1);
  }
  close DEVMAP;
}

# Now write the new entry
print "title  = Linux\n";
print "root   = ($biosdisk,$bootslice)\n";
print "kernel = /boot/vmlinuz$pc97-$insimage-modular vga=$vga $apic debug=2";
print " root=$thisroot" unless ($thisroot eq "");
print "$initrd\n";

# and now dump the remaining input file
print $otherimg;
while (<BGML>) {
  if (m/^\s*password\s*=/i) { $secret = "yes"; }
  s/^\s*title\s*=\s*oldlinux\b/title = Linux-cruft$$/i; # the best we can do
  s/^\s*title\s*=\s*linux\b/title = OldLinux/i;
  print;
}
close BGML;

chmod 0600, "/proc/self/fd/1" unless ($secret eq "no");
