#!/usr/bin/perl

use Cwd qw( realpath );
use File::Basename qw( fileparse );

@cfg = ('.wake', ( (fileparse( realpath($0) ))[1] ) . '.wake');
$mac = {};

$x = '[0-9a-fA-F]';
$macre = "$x$x:$x$x:$x$x:$x$x:$x$x:$x$x";
$ipre = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";

foreach my $cfg (@cfg) {
	open(CFG, $cfg);
	while (<CFG>) {
		next if /^\s*#/;
		next if /^\s*$/;
		
		chomp;
		my($host, $hw, $ip) = split;
		push @{$mac->{lc($host)}}, { MAC => $hw, IP => $ip };
	}
}

if (@ARGV) {
	foreach $host (@ARGV) {
		if ($host =~ /$macre/) {
			print qx(wakeonlan $host);
		}
		elsif (@physical = @{$mac->{lc($host)}}) {
		    foreach my $mac (@physical) {
		        if ($mac->{IP}) {
		            print qx(wakeonlan -i $mac->{IP} $mac->{MAC});
		        }
		        else {
		            print qx(wakeonlan $mac->{MAC});
		        }
		    }
		}
		else {
			print lc($host) . ": no such host in the list.\n";
		}
	}
}
else {
	foreach $host (sort keys %$mac) {
	    $physical = $mac->{lc($host)};
	    foreach my $mac (@$physical) {
	        print "$host -> $mac->{MAC} -> $mac->{IP}\n";
	    }
	}
}

