#!/usr/bin/perl
#--------------------------------------------------------------------
# Copyright (C) 2000, 2001 by MandrakeSoft,
# Pixel <pixel@mandrakesoft.com>,
# Chmouel Boudjnah <chmouel@mandrakesoft.com>, 
# Redistribution of this file is permitted under the terms of the GNU 
# Public License (GPL)
#--------------------------------------------------------------------
# $Id: rebootin,v 1.1.1.1 2003/11/26 19:11:38 at Exp $
#--------------------------------------------------------------------
## description: 
#		Reboot once on a specified image for grub or lilo

use strict;

my $lilo_conf = "/etc/lilo.conf";

my $grub_menu = "/boot/grub/menu.lst";
my $grub_once = "/boot/grub/menu.once";
my @entries;
my $bootloader  = `/usr/sbin/detectloader -q` or die "Can't detect your bootloader\n";chomp $bootloader;
my ($fastboot, $noreboot);

while ( $ARGV[0] =~ /^-/ ) {
    $_ = shift;
    if (/^-f/) {
	$fastboot++;
    } elsif (/^-n/) {
	$noreboot++;
    } else {
	die "Unknow switch $_\n";
    }
}

if ($bootloader =~ /GRUB/) {
    grub_conf();
} elsif ( $bootloader =~ /LILO/) {
    lilo_conf();
} else {
    die "Can't detect your bootloader\n";
}

sub lilo_conf {
    open F, $lilo_conf or die "lilo is not installed ($lilo_conf is missing)\n";
    @entries = map { /=(\S.*)/ } grep { /\s*label=\S*/ } <F>;
    @entries > 0 or die "Bad lilo.conf (no entry found)\n";
    usage() unless $ARGV[0];
    grep /^$ARGV[0]$/, @entries or usage();
    write_fast_boot() if $fastboot;
    system("lilo -R @ARGV"); die "error while wanting to reboot on $ARGV[0]\n" if $?;
    exec "reboot" unless $noreboot;
}    

sub grub_conf {
    open F, $grub_menu or die "grub is not installed ($grub_menu is missing)\n";
    @entries = map { /\s(\S.*)/ } grep { /^title\s/ } my @l = <F>;

    grep { m|^altconfigfile\s.*grub/menu\.once| } @l or die "rebootin is of no use without altconfigfile\n";
    @entries > 0 or die "bad menu.lst (no entry found)\n";
    @ARGV == 1 or usage();
    
    for (my $i = 0; $i < @entries; $i++) { 
	$ARGV[0] eq $entries[$i] and set_grub($i);
    }
    
    print STDERR "$ARGV[0] not found\n";
    usage(); # not found
}

sub set_grub {
    open F, ">$grub_once" or die "can't write rebootin file ($grub_once), verify the rights\n";
    print F "default $_[0]\ntimeout 0\n";
    write_fast_boot() if $fastboot;
    exec "reboot" unless $noreboot;
}

sub usage {
    die "usage: rebootin <label>\n  where <label> is one of " . join(", ", @entries) . "\n";
}

sub write_fast_boot {
    local *F; open F, ">/fastboot"; close F;
}
