* remove needless hash check
[lab.git] / .bin / wake
1 #!/usr/bin/perl
2
3 use Cwd qw( realpath );
4 use File::Basename qw( fileparse );
5
6 @cfg = ('.wake', ( (fileparse( realpath($0) ))[1] ) . '.wake');
7 $mac = {};
8
9 $x = '[0-9a-fA-F]';
10 $macre = "$x$x:$x$x:$x$x:$x$x:$x$x:$x$x";
11 $ipre = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
12
13 foreach my $cfg (@cfg) {
14         open(CFG, $cfg);
15         while (<CFG>) {
16                 next if /^\s*#/;
17                 next if /^\s*$/;
18                 
19                 chomp;
20                 my($host, $hw, $ip) = split;
21                 push @{$mac->{lc($host)}}, { MAC => $hw, IP => $ip };
22         }
23 }
24
25 if (@ARGV) {
26         foreach $host (@ARGV) {
27                 if ($host =~ /$macre/) {
28                         print qx(wakeonlan $host);
29                 }
30                 elsif (@physical = @{$mac->{lc($host)}}) {
31                     foreach my $mac (@physical) {
32                         if ($mac->{IP}) {
33                             print qx(wakeonlan -i $mac->{IP} $mac->{MAC});
34                         }
35                         else {
36                             print qx(wakeonlan $mac->{MAC});
37                         }
38                     }
39                 }
40                 else {
41                         print lc($host) . ": no such host in the list.\n";
42                 }
43         }
44 }
45 else {
46         foreach $host (sort keys %$mac) {
47             $physical = $mac->{lc($host)};
48             foreach my $mac (@$physical) {
49                 print "$host -> $mac->{MAC} -> $mac->{IP}\n";
50             }
51         }
52 }
53