#!/usr/bin/perl

# This file is in the public domain.
# Stuart Henderson, November 2015

use 5.012;
use warnings;
use Text::CSV;
use Getopt::Std;
use open ':std' => ':locale';

my %oui;
our $opt_e = 0;
if (!getopts('e')) {
    die "ERROR: invalid option";
}

sub readin($)
{
        my ($file) = @_;

	my $csv = Text::CSV->new({
		allow_loose_quotes => 1,
		auto_diag => 1,
		binary => 1,
		eol => $/
	});
	my ($registry, $mac, $vendor, $address);
	$csv->bind_columns (\$registry, \$mac, \$vendor, \$address);

	if (open my $fh, "<:encoding(utf8)", "$file") {
		while ($csv->getline ($fh)) {
			$oui{lc($mac)} = $vendor;
		}
		close $fh;
	}
}

sub lookup($)
{
	my $vendor = 'UNKNOWN';
	my $n = lc(shift);
	$n =~ s/[-:]//g;
	while ($n ne '') {
		$n =~ s/.$//;
		if ($oui{$n}) {
			$vendor = $oui{$n};
			last;
		}
	}
	return $vendor;
}

readin('/usr/local/share/mac-vendor/unofficial.csv');
readin('/usr/local/share/mac-vendor/iab.csv');
readin('/usr/local/share/mac-vendor/ma-s.csv');
readin('/usr/local/share/mac-vendor/ma-m.csv');
readin('/usr/local/share/mac-vendor/ma-l.csv');

die("couldn't read any MAC list") unless %oui;

if ($ARGV[0]) {
	while($ARGV[0]) {
		my $m = shift;
		printf "%s (%s)\n", $m, lookup($m);
	}
	exit;
}
while(<STDIN>) {
	chomp;
	my $line = $_;
	# ([0-9a-f]{2}:){5}[0-9a-f]{2}	00:11:22:33:44:55
	# [0-9a-f]{6}-[0-9a-f]{6}	001122-334455 (HP Procurve)
	if ( /(([0-9a-f]{2}[-:]){5}[0-9a-f]{2}|[0-9a-f]{6}-[0-9a-f]{6})/i ) {
		my $m = $1;
		my $vendor = lookup($m);
		if ($opt_e) {
			$line =~ s,$,\t# $vendor,;
		} else {
			$line =~ s,$m,$m ($vendor),;
		}
	}
	print "$line\n";
}
