#!/usr/bin/perl -w

# kernel helper - by dual
# handles the busywork of installing a new kernel
# usage: perl kern_help.pl

use strict;

# See if we're root
chomp(my $user=`whoami`);
die "got root?" unless $user =~ /root/;

# Print warning
print "\n";
print ">>> Waiting 5 seconds before starting...\n";
print ">>> (Ctrl-C to abort)...\n";
print ">>> Did you load your kernel config file?\n";
print "\n";
sleep 5;

# Get the latest kernel version and link to it
chdir "/usr/src";
my @kernels = <*>;
my @sorted = sort(@kernels);
my $latest = pop(@sorted);
unlink "linux";
system("ln -s $latest linux");

# Compile the new kernel
chdir "linux";
system("make && make modules_install");
sleep 3;

# Stick around and take care of the stuff in /boot
system("mount /dev/hda1 /boot");
sleep 1;
system("cp /boot/System.map /boot/System.map.bak");
system("cp /boot/vmlinuz /boot/vmlinuz.bak");
system("cp System.map /boot");
system("cp arch/i386/boot/bzImage /boot/vmlinuz");

# Edit grub.conf
open OLD, "/boot/grub/grub.conf" or die "Can't open grub.conf: $!";
open NEW, ">temp" or die "Can't create temp file: $!";

while (<OLD>) {
	s/vmlinuz/vmlinuz\.bak/;
	print NEW;
}

print NEW "\n";
print NEW "title=$latest\n";
print NEW "root (hd0,0)\n";
print NEW "kernel /vmlinuz root=/dev/hda3 vga=791";

close OLD;
close NEW;

system("mv temp /boot/grub/grub.conf");
system("umount /boot");