#!/usr/bin/perl

use strict;
use Getopt::Long;

my $idsfile = "pci.ids";
my $tablefile = "pcitable";

#############################################################################
# Param:
#		<Vendor ID>:<Product ID>:<Sub Vendor ID>:<Sub Product ID>
# Return:
#		1. if the driver is a module, return the name of module
#		2. if the driver is builtin, return ""
#		3. if the driver not exists, return undef
#############################################################################
sub getModuleByID
{
	my ($vendorID, $productID, $subVendorID, $subProductID)  = split(/:/, $_[0]);
	
	open FILE, $tablefile;
	my @lines = <FILE>;
	close FILE;
	
	my $module;
	
	my $line;
	foreach $line(@lines) {
		chomp $line;
		# skip empty line and comment line
		if(length $line == 0 || substr($line, 0, 1) eq "#" ) {
			next;
		}
		# split
		my @words = split(/[\t ]+/, $line);
		# without sub system
		if(@words == 3) {
			if($words[0] eq "0x$vendorID" && $words[1] eq "0x$productID") {
				$module =  $words[2];
			}
		} elsif(@words == 5) {
			if($words[0] eq "0x$vendorID" && $words[1] eq "0x$productID"
				&& $words[2] eq "0x$subVendorID" && $words[3] eq "0x$subProductID" ) {
				$module =  $words[4];
			}
		}
	}
	if(!defined $module) {
		return "UNKNOWN";
	} elsif( $module eq "\"\"") {
		return "BUILTIN";
	} else {
		return substr($module, 1, length($module)-2);
	}
}

#######################################################################

open FILE, $idsfile;
my @lines = <FILE>;
close FILE;

my $vendorID;
my $productID;
my $subVendorID;
my $subProductID;
my $vendorName;
my $productName;
my $moduleName;

my $line;
foreach $line(@lines) {
	chomp($line);
	if(length $line <= 0) {
		next;
	}
	my $c = substr($line, 0, 1);
	if($c eq "#" || $c eq "C") {
		next;
	}
	
	my @words = split(/\t|  /, $line);
	

	# vendor line
	if(length($words[0]) > 0) {
		$vendorID = $words[0];
		$vendorName = $words[1];
	}
	# product line
	elsif(length($words[1]) > 0) {
		$productID = $words[1];
		$productName = $words[2];
		$moduleName = getModuleByID("$vendorID:$productID");
		print STDOUT "$vendorID\t$productID\t\t\t$moduleName\t$vendorName\t$productName\n";
	}
	# sub system line
	else {
		($subVendorID, $subProductID) = split(/ /, $words[2]);
		$productName = $words[3];
		$moduleName = getModuleByID("$vendorID:$productID:$subVendorID:$subProductID");
		print STDOUT "$vendorID\t$productID\t$subVendorID\t$subProductID\t$moduleName\t$vendorName\t$productName\n";
	}
	
	
}
