#!/usr/bin/perl

BEGIN {

    require '/usr/sec/lib/SecBinLog.pm';
    SecBinLog::sb_log(); # Writes an entry to /var/log/legacy/sec-bin.log
}


use strict;
use warnings;
use Getopt::Long;

my $domain;

GetOptions(
        'getusername|u=s'        =>      \$domain,         #which step to run
        );


if($domain){
  print "Log sample"."\n";
  my $data = `tail -10000 /var/log/domlogs/global_log | grep $domain | tail -50`;
  print $data;
  my $getuser = `grep -i $domain /etc/userdomains | awk -F ': ' {'print \$2'} | uniq `;
  print $getuser;
}else{
  my $data = 0;
  $data = `tail -10000 /var/log/domlogs/global_log | awk {'print \$2'} | sort | uniq -c | sort -nr | head`;
  print "$data";
  if($data eq ''){
    print "Oops. No domain found. Are you sure there's data in the global_log?"."\n"."Are logs running?"."\n";
    exit 1;
  }else{
  # Perl 5.10 doesn't know that split/map/etc return a list, so [] says to put it in an arrayref, and @{} dereferences it...
  # essentially fooling perl into thinking it was passed an array. (Else it returns an error that arg must be an array.)
  my $domain = shift @{[ (split /\n/, $data) ]};
    $domain =~ s/^.+\s//;
    $domain =~ s/www\.//g;
    if($domain =~ /^-/ ){
      print "\n"."$domain does not appear to be a valid domain"."\n";
    }else{
    my $getuser = `grep -i $domain /etc/userdomains | awk -F ': ' {'print \$2'} | uniq `;
    print "\n$domain has a username of $getuser\n";
    }
  }
}
exit 0;
