#!/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

use strict;

my ($fastboot, $noreboot, $listlabels);

while ( $ARGV[0] =~ /^-/ ) {
    $_ = shift;
    if (/^(-f)|(--fastboot)$/) {
	$fastboot++;
    } elsif (/^(-n)|(--noreboot)$/) {
	$noreboot++;
    } elsif (/^(-l)|(--list)$/) {
	$listlabels++;
    } elsif (/^(-h)|(--help)$/) {
	show_help();
    } else {
	die "Unknow switch $_\n";
    }
}
die "Insufficient arguments" unless $ARGV[0] || $listlabels;

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

my @entries;

my $lilo_boot = `/usr/sbin/detectliloboot.sh`
  or die "Can't get boot device from lilo.conf\n";
chomp $lilo_boot;

my $bootloader  = `/usr/sbin/detectloader.sh $lilo_boot`
  or die "Can't detect your bootloader\n";
chomp $bootloader;

die "Lilo is not installed in $lilo_boot\n"
  if $bootloader != "lilo";


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";

list_labels() if $listlabels;

grep /^$ARGV[0]$/, @entries
  or die "Unknown label \"$ARGV[0]\"\n";

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 show_help {
  die <<EOF
rebootin - reboots the machine using a particular Boot Loader entry

usage: rebootin [options] <label>
<filename> must specify seekable regular file or device.

Options:
  -f, --fastboot                    reboot in fastboot mode.
  -n, --noreboot                    don't reboot immediately.
  -l, --list                        list available labels.
  -h, --help                        show this text and exit.

Rebootin currently works only with LILO.

Report bugs to http://bugs.altlinux.ru/

EOF
}

sub list_labels {
    die join("\n", @entries) . "\n";
}

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