eval '(exit $?0)' && eval 'exec perl -w -S $0 ${1+"$@"}'
                  && eval 'exec perl -w -S $0 $argv:q'
                  if 0;

use strict;

use Getopt::Long;
use File::Basename;

Getopt::Long::Configure(qw(no_ignore_case bundling require_order));

use vars qw($script_top_dir);
BEGIN {
  # Make a spirited attempt to find where our libraries, etc are.
  if (-l $0) {
    $script_top_dir = dirname(readlink($0));
  } else {
    $script_top_dir = dirname $0;
  }
}

use lib "$script_top_dir";

use GratiaReporting::Reporter;
use GratiaReporting::Data;

my $options = {};
my $master_vo_list = {};
my $alt_vo_list = {};
my $osg_users_script = "$script_top_dir/osg-users";
my $merge = 1;
my @wanted_vos = ();
my @test_addresses = ( 'Philippe Canal <pcanal@fnal.gov>' );
my $prog = basename($0);

GetOptions($options,
           "compare-period|comparison-period=s",
           "data-file-precedence|p|r",
           "data-source|D=s@",
           "debug|d",
           "help|h|?",
           "merge|m",
           "monthly|M",
           "production",
           "target-period=s",
           "test|t",
           "verbose",
           "vo|v=s@" => sub { push @wanted_vos, lc $_[1] },
           "weekly|W",
           "yearly|Y"
          ) or do { print STDERR "ERROR: $@"; usage(1); };

$options->{"help"} and usage(1);

# Check options with an effect on each other:
if ($options->{production} and $options->{test}) {
  print STDERR "INFO: test option negates production option.\n";
  delete $options->{production};
}

if ($options->{debug} and not $options->{test}) {
  $options->{production} = 1;
}

$merge = 0 if ($options->{"data-file-precdence"});

my $reporter = new GratiaReporting::Reporter( debug => $options->{debug},
                                              verbose => $options->{verbose},
                                              test => $options->{test}
                                            );

my @extra_args = ();
if ($options->{"target-period"}) {
  push @extra_args, "--target-period", $options->{"target-period"};
}
if ($options->{"compare-period"}) {
  push @extra_args, "--compare-period", $options->{"compare-period"};
}

if (not scalar @ARGV) {
  push @ARGV, "/etc/gratia/gratia-reporting/all-vos.dat";
}

# Parse reporting data from all sources
my $reporting_data =
  new GratiaReporting::Data( debug => $options->{debug},
                             verbose => $options->{verbose},
                             data_source => $options->{"data-source"}
                           );


# Read list of VOs and email addresses
foreach my $dat_file (@ARGV) {
  print "INFO: attemping to read data file $dat_file\n";
  if (not open(DAT_SOURCE, $dat_file)) {
    print STDERR "ERROR: Unable to open data file $dat_file\n";
    next;
  }
  my $dat_source = join('', <DAT_SOURCE>);
  close DAT_SOURCE;
  my %tmp_hash = eval $dat_source;
  if ($@) {
    print STDERR "ERROR: Problem reading collector data file $dat_file: $@\n";
    next;
  }
  foreach my $vo (sort keys %tmp_hash) {
    # Filter?
    next if (lc $vo ne "all") and
      scalar @wanted_vos and
        not grep /^\Q$vo\E$/i, @wanted_vos;
    if (exists $master_vo_list->{lc $vo}) {
      if ($merge) {
        my $email_hash = {};
        foreach my $email (@{$master_vo_list->{lc $vo}}, @{$tmp_hash{$vo}->{mail} || []}) {
          $email_hash->{$email} = 1;
        }
        $master_vo_list->{lc $vo} = [ sort keys %$email_hash ]; # merge
      }
    } else {
      $master_vo_list->{lc $vo} = [ sort @{$tmp_hash{$vo}->{mail} || []} ];
    }
    if (exists $alt_vo_list->{lc $vo}) {
      if ($merge) {
        my $vo_hash = {};
        foreach my $alt_vo (@{$alt_vo_list->{lc $vo}}, @{$tmp_hash{$vo}->{"alt-vos"} || []}) {
          $vo_hash->{$alt_vo} = 1;
        }
        $alt_vo_list->{lc $vo} = [ sort keys %$vo_hash ]; # merge
      }
    } else {
      $alt_vo_list->{lc $vo} = [ sort @{$tmp_hash{$vo}->{"alt-vos"} || []} ];
    }
  }
}

foreach my ${vo_key} (sort keys %$vo_data) {
  unless ($master_vo_list->{lc $vo_key} or
          (scalar @wanted_vos and
           not grep /^\Q$vo_key\E$/i, @wanted_vos)) {
    print "INFO: Added VO $vo_key to list\n";
    $master_vo_list->{lc $vo_key} = [];
  }
}

if ($options->{"test"}) {
  $master_vo_list->{"all-vos-test"} = [ @test_addresses ]
    unless exists $master_vo_list->{"all-vos-test"};
}

foreach my ${primary_email} (sort keys %${people_data}) {
  my $person = $people_data->{$primary_email};
  my $vo_rep_name_reports = {};
  foreach my ${vo_rep_name} (@{$person->{reporting_names}}) {
    my ($vo, $reporting_name) = ($vo_rep_name =~ m&^([^:]+):(.*)$&);
    $vo = lc $vo;
    $vo_rep_name_reports->{$vo} = {} unless $vo_rep_name_reports->{$vo};
    $vo_rep_name_reports->{$vo}->{$reporting_name} = "LOCAL";
  }
  foreach my ${vo_rep_name} (@{$person->{vo_reporting_names}}) {
    my ($vo, $reporting_name) = ($vo_rep_name =~ m&^([^:]+):(.*)$&);
    $vo = lc $vo;
    my ($matching_vo_key) = (grep { lc $_ eq $vo } keys %$vo_data);
    next if (grep { lc $_ eq $reporting_name } @{$vo_data->{$matching_vo_key}->{alt_vos}});
    $vo_rep_name_reports->{$vo} = {} unless $vo_rep_name_reports->{$vo};
    if ($vo_rep_name_reports->{$vo}->{$reporting_name}) {
      $vo_rep_name_reports->{$vo}->{$reporting_name} = "BOTH";
    } else {
      $vo_rep_name_reports->{$vo}->{$reporting_name} = "OIM";
    }
  }
  foreach my $vo (sort keys %$vo_rep_name_reports) {
    my @local_only_entries = map { ($vo_rep_name_reports->{$vo}->{$_} eq "LOCAL")?$_:() } (sort keys %{$vo_rep_name_reports->{$vo}});
    foreach my $name (@local_only_entries) {
      print "OIM_WARNING: $primary_email report request for $vo:$name is missing from OIM.\n";
    }
    my @oim_only_entries = map { ($vo_rep_name_reports->{$vo}->{$_} eq "OIM")?$_:() } (sort keys %{$vo_rep_name_reports->{$vo}});
    foreach my $name (@oim_only_entries) {
      print "OIM_WARNING: $primary_email report request for $vo:$name is in OIM only.\n"
        if $options->{verbose};
    }
    my @command =  ("$osg_users_script", "-v", "$vo", "--aux-db-type=none", "-s", "-V", @extra_args);
    push @command, map { ( "-D", $_) } @{$options->{"data-source"}} if $options->{"data-source"};
    if ($options->{monthly}) {
      push @command, "-t", "month";
    } elsif ($options->{yearly}) {
      push @command, "-t", "year";
    }
    push @command, map { ("--reporting-name", "$vo:$_") } (sort keys %{$vo_rep_name_reports->{$vo}});
    my @address_list = ();
    if ($options->{production}) {
      push @address_list, $person->{contact_string}, @{$master_vo_list->{"all"} || [] };
    } elsif ($options->{test}) {
      push @address_list, @{$master_vo_list->{"all-vos-test"}};
    }
    $reporter->invoke(\@command, [ map { ("-m", $_) } @address_list ]);
  }
}

foreach my $vo (sort keys %$master_vo_list) {
  next if (lc $vo eq "all" or lc $vo eq "all-vos-test");
  my @command = ("$osg_users_script", "-v", "$vo", "--aux-db-type=none", "-s", "-V", @extra_args);
  push @command, map { ( "-D", $_) } @{$options->{"data-source"}} if $options->{"data-source"};
  if ($options->{monthly}) {
    push @command, "-t", "month";
  } elsif ($options->{yearly}) {
    push @command, "-t", "year";
  }
  my $email_hash = {};
  my @email_list = ();
  if ($options->{production}) {
    push @email_list, @{$master_vo_list->{$vo}}, @{$master_vo_list->{"all"} || [] };
  } elsif ($options->{"test"}) {
    push @email_list, @{$master_vo_list->{"all-vos-test"}};
  }
  foreach my ${email} (@email_list) {
    my ($address) = ($email =~ m&<([^>]+)>&);
    $email_hash->{$email} = $address || $email;
  }
  foreach my ${email} (sort keys %$email_hash) {
    # Check whether we have information about this person from OIM
    if (exists $people_data->{$email_hash->{$email}} and
        $people_data->{$email_hash->{$email}}->wants_vo_report_oim($vo)) {
      print "INFO: Matched $email_hash->{$email} in OIM contacts list for VO $vo.\n"
        if $options->{verbose};
    } elsif (exists $people_data->{$email_hash->{$email}} and
             $people_data->{$email_hash->{$email}}->wants_all_vos()) {
      print "INFO: $email_hash->{$email} wants all VO reports: added to report for VO $vo.\n"
        if $options->{verbose};
    } else {
      print "OIM_WARNING: Local contact $email not found in OIM contacts list for VO $vo.\n";
    }
  }
  if ($options->{production}) { # Only
    # Check whether OIM knows something we don't
    foreach my $person (sort keys %$people_data) {
      print "INFO: Checking $person in OIM data\n" if $options->{verbose};
      #    print "INFO: person data for $person:\n",
      #      '-' x 72, "\n",
      #        $people_data->{$person}->info(),
      #        '-' x 72, "\n" if $options->{verbose};
      if ($people_data->{$person}->wants_vo_report_oim($vo)) {
        if (grep m&$person&i, %$email_hash) {
          print "INFO: OIM contact $people_data->{$person}->{full_name} matches data-file email $person for VO $vo.\n"
            if $options->{verbose};
        } else {
          # Add person to send list.
          $email_hash->{sprintf("%s <%s>",
                                $people_data->{$person}->{full_name},
                                $person)} = $person;
        }
      } elsif ($people_data->{$person}->wants_all_vos()) {
        print "INFO: OIM contact $people_data->{$person}->{full_name} wants all VO reports: added to report for VO $vo.\n"
          if $options->{verbose};
        # Add person to send list.
        $email_hash->{sprintf("%s <%s>",
                              $people_data->{$person}->{full_name},
                              $person)} = $person;
      }
    }
  }
  @email_list = map { ('-m', $_) } sort keys %$email_hash;
  print "INFO: compiling and distributing report for VO $vo to: ";
  if (scalar keys %$email_hash) {
    print join(", ", sort keys %$email_hash),"\n";
  } else {
    print "<none>\n";
  }
  $reporter->invoke(\@command, \@email_list);
}

1;

sub usage {
  print STDERR <<EOF;
Usage: $prog [<options>] [<local-data-file>]

EOF
  GratiaReporting::Reporter::usage(\*STDERR);
  print STDERR <<EOF;

$prog options:

  --help
   -h
   -\?

    This help.

  --compare-period <time-string>
  --comparison-period <time-string>

    Time period from which to calculate deltas to target.

  --data-file-precedence
   -p
   -r

    Do not merge (use local file configuration only). Negates effect of
    --merge.

  --data-source <data-source>
   -D <data-source>

    Specify a file or remote XML data source.

  --merge
   -m

    Merge local file configuration data and OIM, XML sources (default).

  --monthly
   -M

    Monthly report.

  --production

    Send email to all requesting parties as ascertained from all
    specified information sources.  Note: the presence of the debug
    option combined with the lack of the "test" option will activate the
    production option but not invoke any reports.

  --target-period <time-string>

    Time period upon which to report.

  --test
   -t

    Send email only to 'all-vos-test' group (default no email). If set,
    negates, "production" option.

  --vo <VO>
   -v <VO>

    Add VO <VO> to list upon which to report.

  --weekly
   -W

    Weekly report.

  --yearly
   -Y

    Yearly report.


EOF
  if (defined $_[0]) {
    exit($_[0]);
  }
}

__END__

### Local Variables:
### mode: cperl
### End:
