#!/usr/bin/perl

use strict;
use warnings;

use Socket;
use SiteSummary;

use vars qw(%hostmap);

$ENV{PATH} .= ':/usr/sbin';
my @hostlist = `netgroup -h shutdown-at-night-hosts`;
chomp @hostlist;
map { $hostmap{$_} = 1; } @hostlist;

for_all_hosts(\&host_handler);
exit(0);

sub host_handler {
    my $hostid = shift;
    my $ipaddr = SiteSummary::get_primary_ip_address($hostid);
    my $fqdn = scalar gethostbyaddr(inet_aton($ipaddr), AF_INET);
    if ($fqdn) {
        my $mac = (get_ether_hwaddr($hostid))[0];
        if (exists $hostmap{$fqdn}) {
            print "$fqdn $mac\n";
        }
    }
}

sub get_ether_hwaddr {
    my $hostid = shift;
    my $path = get_filepath_current($hostid, "/system/ifconfig-a");
    if (open(FILE, "<", $path)) {
        my $sysinfo = 0;
        my @hwaddr = ();
        while (<FILE>) {
            chomp;
            if (m/Link encap:Ethernet  HWaddr (.+\S)\s*$/) {
                push(@hwaddr, $1);
            }
        }
        close(FILE);
        return @hwaddr;
    } else {
        return undef;
    }
}
