#!/usr/bin/perl
# $Id: detectloader,v 1.5 2004/06/24 00:19:22 at Exp $

=head1	NAME

detectloader - detect what type of loader you have on your disk

=head1	DESCRIPTION

detectloader detects the type of the boot loader you have on your MBR.  It
finds the first disk via /proc/partitions and looks via the magic serial what
kind of boot loader you have installed.  If neither LILO nor GRUB is found on
MBR, try partitions too.

=head1	LIMITATION

Supports only grub and lilo.  Patches welcome for other boot loaders.

=head1	COPYRIGHT

Copyright (C) 2003 by ALT Linux Team, Alexey Tourbin <at@altlinux.org>.

Copyright (C) 2000, 2001, 2002 by MandrakeSoft, Pixel <pixel@mandrakesoft.com>
and others MandrakeSoft folks.

Redistribution of this file is permitted under the terms of the GNU 
Public License (GPL).

=cut

use bootloader_utils qw(partitions typeOfMBR);
use strict;

use Getopt::Long qw(GetOptions);
GetOptions "q|quiet" => \my $quiet
	or die "usage: $0 [-q|--quiet]\n";

sub warning {
	warn "@_\n" unless $quiet;
}

sub read_skiplist {
	open my $fh, "/etc/bootloader/skiplist" or return;
	my @list;
	local $_;
	while (<$fh>) {
		next if /^#/;
		/\S+/ and push @list, $&;
	}
	return @list;
}

sub detect {
	my %known_loaders = map { $_ => 1 } qw(grub lilo);
	my %skiplist = map { $_ => 1 } read_skiplist();
	my (@disks, @partitions);
	foreach (partitions()) {
		next if $skiplist{$$_{dev}};
		next if $$_{media} eq "cdrom";
		$$_{dev} =~ /\d$/
			? push @partitions, $_
			: push @disks, $_
			;
	}
	foreach my $disk (@disks) {
		my $loader = typeOfMBR($disk);
		if ($known_loaders{$loader}) {
			warning "$0: $$disk{dev}: $loader";
			return $loader;
		}
	}
	warning "no bootloader on MBR, trying partitions!";
	open my $pipe, "-|", "fdisk", "-l",
		or warning "$0: fdisk not available"
		and return;
	while (<$pipe>) {
		next unless m#^/dev/(\w+\d+)\s+\*\s+#;
		next if $skiplist{$1};
		my ($partition) = grep { $$_{dev} eq $1 } @partitions;
		next unless $partition;
		my $loader = typeOfMBR($partition);
		if ($known_loaders{$loader}) {
			warning "$0: $$partition{dev}: $loader";
			return $loader;
		}
	}
	return;
}

my $loader = $ENV{DEFAULT_LOADER} || detect();
print uc($loader) . "\n";
