#!/usr/bin/perl -w

use strict;
use XML::Parser::PerlSAX;

my $config_file = "/etc/recoverycd/hardwares.xml";
my $parser = XML::Parser::PerlSAX->new();
	
$parser->parse(	Source => { SystemId => $config_file },
	DocumentHandler => ProbeHardwareHandler->new() );

###########################################################################
# class ProbeHardwareHandler
# this class is used to fill the SAX interface to probe hardwares
###########################################################################
package ProbeHardwareHandler;

use strict;

my %device;
my $cdata;

my @probed_devices;

sub new
{
	my $type = shift;
	my $this = {};
	
	$this->{'Type'} = $type;
	
	bless $this;
}

sub end_document
{
	my $dev;
	foreach $dev (@probed_devices) {
		print STDOUT $dev, "\n";
	}
}

sub start_element
{
	my ($self, $properties) = @_;
	my $element_name = $properties->{'Name'};
	my %attributes = %{$properties->{'Attributes'}};
	
	if( $element_name eq "vendor") {
		$device{$element_name} = $attributes{'name'};
	} elsif ( $element_name eq "device" ) {
		$device{$element_name} = $attributes{'name'};
	}
}

sub end_element
{
	my ($self, $properties) = @_;
	my $element_name = $properties->{'Name'};

	if( $element_name eq "vendor") {
		%device = ();
	} elsif( $element_name eq "device" ) {
		probe_device();
		%device = ("vendor", $device{"vendor"});
	} elsif( $element_name eq "module" || $element_name eq "probe_method"
		|| $element_name eq "install_method" || $element_name eq "pci_id") 
	{
		$device{$element_name} = $cdata;
	}
}

sub characters
{
	my ($self, $properties) = @_;
	
	$cdata = $properties->{'Data'};
}

sub probe_device
{
	if(defined $device{'pci_id'}) {
		probe_pci_device()
	}
	return;
}
sub probe_pci_device
{
	open FILE, "/proc/bus/pci/devices";
	my @lines =<FILE>;
	close FILE;
	
	my $found = 0;
	my $line;
	foreach $line (@lines) {
		my @words = split(/[ \t]+/, $line);
		if($words[1]  eq $device{'pci_id'}) {
			$found = 1;
			last;
		}
	}
	if($found == 0) {
		return;
	}
	
	system("modprobe -q $device{'module'} 1>>/dev/null 2>>/dev/null");
	if ($? == 0) {
		my $ret = grep(/^$device{'module'} /, `lsmod 2>>/dev/null`);
	
		if($ret) {
			$probed_devices[@probed_devices] = "$device{'vendor'} - $device{'device'}";
		}
	}
	
	return;
}
