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 FileHandle;

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

sub expandSites(\@);

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

GetOptions($options,
           "compare-period|comparison-period=s",
           "data-source|D=s@",
           "debug|d",
           "exclusive-mail|m=s@",
           "extra-mail|e=s@",
           "for-user|u=s@",
           "grid-type|g=s@",
           "help|h|?",
           "monthly|M",
           "production",
           "service=s@",
           "site-name|s=s@",
           "target-period=s",
           "test|t",
           "verbose|v",
           "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->{production} and $options->{"exclusive-mail"}) {
  print STDERR "INFO: exclusive-mail option negates production option.\n";
  delete $options->{production};
}

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

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"};
}

my $wanted_sites = {};
foreach my $site (@{$options->{"site-name"}}) {
  $wanted_sites->{$site} = 1;
}

my $wanted_grid_types = {};
foreach my $grid_type (@{$options->{"grid-type"}}) {
  $wanted_grid_types = 1;
}
unless (scalar keys %$wanted_grid_types) { # Default
  $wanted_grid_types->{OSG} = 1;
}

my $wanted_services = {};
foreach my $service (@{$options->{service}}) {
  $wanted_services->{$service} = 1;
}
unless (scalar keys %$wanted_services) { # Defaults
  $wanted_services->{CE} = 1;
  $wanted_services->{"Hidden CE"} = 1;
  $wanted_services->{"Hidden CE/SE"} = 1;
}

my $all_sites = not scalar keys %{$wanted_sites};

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

# Construct the command line(s) and invoke.
my @base_command = ("$osg_users_script",
                    "-s",
                    "-S",
                    "--aux-db-type=none",
                    @extra_args,
                    ($options->{"data-source"})?(map { ("-D", $_) } @{$options->{"data-source"}}):());
my @base_mail_opts = ();
if ($options->{"exclusive-mail"}) { # Short-circuit people list.
  my @command = @base_command;
  my @mail_opts = @base_mail_opts;
  if ($options->{monthly}) {
    push @command, "-t", "month";
  } elsif ($options->{yearly}) {
    push @command, "-t", "year";
  }
  push @command, map { ("--site-name", $_) } expandSites(@{$options->{"site-name"}})
    if $options->{"site-name"};
  push @mail_opts, map { ("-m", $_) } @{$options->{"exclusive-mail"}};
  $reporter->invoke(\@command, \@mail_opts);
} else { # Standard -- take main lead from .dat files and OIM.
  if ($options->{monthly}) {
    push @base_command, "-t", "month";
  } elsif ($options->{yearly}) {
    push @base_command, "-t", "year";
  }
  $options->{"extra-mail"} = [] unless $options->{"extra-mail"};
  if ($options->{production}) { # People wanting "all reports"
    push @{$options->{"extra-mail"}},
      map { (exists $people_data->{$_}->{all_reports}->{site} and
             $people_data->{$_}->{all_reports}->{site})?($_):()} keys %{$people_data};
  }
  push @base_mail_opts, map { ("-m", $_) } @{$options->{"extra-mail"}} if $options->{"extra-mail"};
  my @user_list;
  if ($options->{"for-user"}) { # mini-short-circuit
    @user_list = map {
      if (exists $people_data->{$_}) {
        ($_)
      } else {
        print STDERR "WARNING: specified user $_ not known -- ignoring.\n";
        ()
      }
    } @{$options->{"for-user"}};
  } else {
    @user_list = keys %$people_data;
  }
  foreach my $primary_email (sort @user_list) {
    my @command = @base_command;
    my @mail_opts = @base_mail_opts;
    my $person = $people_data->{$primary_email};
    if ($person->{all_reports} and $person->{all_reports}->{site}) {
    }
    if ($options->{test}) {
      push @mail_opts, map { ("-m", $_) } @test_addresses
        if scalar @test_addresses;
    } elsif ($options->{production}) {
      push @mail_opts, "-m", "$person->{contact_string}";
    }
    if ($person->{site_vos}) { # VO-specific site lists.
      foreach my $vo (sort (map { lc $_ } (keys %{$person->{site_vos}}))) {
        my @looped_cmd = (@command, "-v", $vo);
        next unless $person->{site_vos}->{$vo};
        push @looped_cmd, (map { ("--site-name", $_) }
                           expandSites(@{$person->{site_vos}->{$vo}}));
        $reporter->invoke(\@looped_cmd, \@mail_opts);
      }
    }
    my @wanted_sites = map { ("--site-name", $_) }
      expandSites(@{$person->{sites}}) if $person->{sites};
    next unless @wanted_sites and scalar @wanted_sites;
    push @command, @wanted_sites;
    $reporter->invoke(\@command, \@mail_opts);
  }
}

1;

sub expandSites(\@) {
  my $siteList = shift;
  my %u_sites = ();

# hk modification to deal with global or local situation
  my $bool_glocal = grep /default/, @{$options->{"data-source"}};
  if ( $bool_glocal ) {
# hk mod

  foreach my $site (@$siteList) {
    if ($site =~ m&^all$&i) {
      map { $u_sites{$_} = 1 } keys %$site_data;
    } else {
      next unless ($site and
                   $site_data->{$site} and
                   ($all_sites or $wanted_sites->{$site})); # Want this site?
      next if ($site_data->{$site}->{grid_type} and not
               $wanted_grid_types->{$site_data->{$site}->{grid_type}}); # Want this grid type?
      next if ($site and
               $site_data->{$site} and
               exists $site_data->{$site}->{services} and
               not grep { $wanted_services->{$_} } keys %{$site_data->{$site}->{services}});
      $u_sites{$site} = 1;
    }
  }

# hk mod
} else {
  foreach my $site (@$siteList) {
      $u_sites{$site} = 1;
    }
}
# hk mod

  return sort keys %u_sites;
}

sub usage {
  my $test_addresses_string = join(", ", @test_addresses);
  print STDERR <<EOF;
Usage: $prog [<options>] [<local-data-file>]

Options marked (+) may be specified multiple times, arguments being
cumulative.

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-source <data-source>
   -D <data-source>

    Specify a file or remote XML data source.

  --exclusive-mail <address> (+)
   -m <address> (+)

    Specify an address to which to send reports *instead* of those
    gleaned from other data sources (eg OIM).

  --extra-mail <address> (+)
   -e <address> (+)

    Specify an address to which to send reports *in addition* to those
    gleaned from other data sources (eg OIM).

  --for-user <address> (+)
   -u <address> (+)

    Process only those reports for which <address> is a recipient.

  --grid-type <grid> (+)
   -g <grid> (+)

    Process resports only for those sites in grid <grid>.

  --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.

  --service <service> (+)

    Process reports only for those sites offering service <service>.

  --site-name <site> (+)
   -s <site> (+)

    Process reports only for <site>.

  --target-period <time-string>

    Time period upon which to report.

  --test
   -t

    Send email only to test addresses (currently $test_addresses_string). If set,
    negates, "production" option.

  --weekly
   -W

    Weekly report.

  --yearly
   -Y

    Yearly report.


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

__END__

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