#!/usr/bin/perl
# $Id: grub-ins.pl,v 1.1 1999/08/30 15:08:23 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;
}

# try to figure out the boot partition ("slice").
# XXX Assume it's on the first disk !!! (see "hd0," below)
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.,,;
$bootslice = $bootslice - 1;

print "title  = Linux\n";
print "root   = (hd0,$bootslice)\n";
print "kernel = /boot/vmlinuz$pc97-$insimage-modular $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");
