#! /usr/bin/perl -w

my @directoriesToSearch = ( '/etc/xen', '/etc/xen/iscsi_configs' );
my %output;


sub getConfigurationFiles {
   my $directory = shift;
   my @files;
   if ( opendir(my $dh, $directory) ) {
      @files = map{ "$directory/$_" } grep { /((\.cfg)|(\.hvm))$/ } readdir($dh);
      closedir $dh;
   } else {
      warn "can't opendir $directory: $!";
   }
   return @files;
}


sub parseConfigFile {
   my ($content,$hostname) = @_;
   if ( $content =~ m/vif\s*=\s*\[([^\]]+)/gi ) {
      my $vifs = $1;
      while ( $vifs =~ m/mac\s*=\s*([a-z0-9:-]+)/gi ) {
         my $mac = $1;
         $mac .= '-Dup' if  $output{'mac'}{$mac};
         $output{'mac'}{$mac} = $hostname;
      }
   }
}

sub processConfigFile {
   my $filename = shift;
   open CONF, "<$filename" or die "Could not read $filename: $!\n";
   my $contents = join( '', <CONF>); # slurp the file contents in
   close CONF;
   &parseConfigFile( $contents, $filename );
}

my @files;
foreach my $dir ( @directoriesToSearch ) {
   push @files, getConfigurationFiles( $dir );
}

foreach my $file ( @files ) {
   &processConfigFile( $file );
}

foreach my $key ( keys %output ) {
   print "$key\n";
   foreach my $item ( keys %{$output{$key}} ) {
      print "$item\t$output{$key}{$item}\n";
   }
}

1;
