package pci_probing::main;

use pci_probing::pcitable;
use pci_probing::pci_class;
use log;

1;

sub get_type($) {
    my ($first_num) = @_;
    my ($bus) = $first_num >> 8;
    $first_num &= 0xff;
    my ($device) = $first_num >> 3;
    my ($function) = $first_num & 0x7;

    local *F;
    open F, sprintf("/proc/bus/pci/%02x/%02x.%x", $bus, $device, $function) or die '';
    seek F, 10, 0 or die '';
    my $a; read(F, $a, 2) or die '';
    $pci_probing::pci_class::classes{unpack "S", $a} || 'unknown';
}

sub probe($;$) {
    my ($type, $more) = @_;
    my @l;
    my $f = "/proc/bus/pci/devices";
    local *F;
    open F, $f or return; 
    foreach (<F>) {
	my ($a, $b) = /(\S+)\s+(\S+)/ or next;
	my $t = $type ? get_type(hex $a) : '.';
	!$type || $t =~ /$type/i or next;
        if (my $i = $pci_probing::pcitable::ids{hex $b}) {
	    push @l, $type eq '.' ? [ $t, @$i ] : $more ? [ $_, @$i ] : $i;
	} elsif ($type eq '.') {
	    $b =~ /(.{4})(.{4})/;
	    push @l, [ "unknown", $t eq "unknown" ? $t : "Vendor=0x$1 Device=0x$2", "unknown" ];
	}
    }
    @l;
}

sub list { map { "$_->[1] ($_->[0] $_->[2])" } probe('.'); }
