#!/usr/bin/perl -w
######################################################################
#
# $Id: webjob-jqd-list-groups,v 1.14 2012/01/07 08:01:19 mavrik Exp $
#
######################################################################
#
# Copyright 2007-2012 The WebJob Project, All Rights Reserved.
#
######################################################################
#
# Purpose: List currently defined groups.
#
######################################################################

use FindBin qw($Bin $RealBin); use lib ("$Bin/../lib/perl5/site_perl", "$RealBin/../lib/perl5/site_perl", "/usr/local/webjob/lib/perl5/site_perl", "/opt/local/webjob/lib/perl5/site_perl");

use strict;
use File::Basename;
use Getopt::Std;
use WebJob::JqdRoutines;
use WebJob::KvpRoutines 1.029;
use WebJob::Properties 1.035;

BEGIN
{
  ####################################################################
  #
  # The Properties hash is essentially private. Those parts of the
  # program that wish to access or modify the data in this hash need
  # to call GetProperties() to obtain a reference.
  #
  ####################################################################

  my (%hProperties);

  ####################################################################
  #
  # Initialize regex variables.
  #
  ####################################################################

  $hProperties{'CommonRegexes'} = PropertiesGetGlobalRegexes();

  ####################################################################
  #
  # Define helper routines.
  #
  ####################################################################

  sub GetProperties
  {
    return \%hProperties;
  }
}

######################################################################
#
# Main Routine
#
######################################################################

  ####################################################################
  #
  # Punch in and go to work.
  #
  ####################################################################

  my ($phProperties);

  $phProperties = GetProperties();

  $$phProperties{'Program'} = basename(__FILE__);

  ####################################################################
  #
  # Get Options.
  #
  ####################################################################

  my (%hOptions);

  if (!getopts('G:', \%hOptions))
  {
    Usage($$phProperties{'Program'});
  }

  ####################################################################
  #
  # A group file, '-G', is optional.
  #
  ####################################################################

  $$phProperties{'GroupsFile'} = (exists($hOptions{'G'})) ? $hOptions{'G'} : "/var/webjob/config/jqd/groups";

  ####################################################################
  #
  # Create group queue map.
  #
  ####################################################################

  my (%hGroupMap);

  %hGroupMap = ();

  if (-f $$phProperties{'GroupsFile'})
  {
    my $sKeyRegex = $$phProperties{'CommonRegexes'}{'Group'};
    my $sUnitRegex = "(?:" . $$phProperties{'CommonRegexes'}{'GroupToken'} . "|" . $$phProperties{'CommonRegexes'}{'ClientId'} . ")";
    my $sValueRegex = "(?:|$sUnitRegex(?:,$sUnitRegex)*)"; # Empty groups are allowed.
    my %hLArgs =
    (
      'File'           => $$phProperties{'GroupsFile'},
      'Properties'     => \%hGroupMap,
      'Template'       => { $sKeyRegex => $sValueRegex, },
      'VerifyValues'   => 1,
    );
    if (!KvpGetKvps(\%hLArgs))
    {
      print STDERR "$$phProperties{'Program'}: Error='$hLArgs{'Error'}'\n";
      exit(2);
    }
  }
  else
  {
    print STDERR "$$phProperties{'Program'}: Error='File ($$phProperties{'GroupsFile'}) does not exist or is not regular.'\n";
    exit(2);
  }

  ####################################################################
  #
  # Conditionally resolve each group to determine if it contains the
  # member. If a member was not specified, just list all the groups.
  #
  ####################################################################

  if (scalar(@ARGV) > 0)
  {
    my %hMembersDone = ();
    foreach my $sMember (sort(@ARGV))
    {
      next if ($hMembersDone{$sMember}++);
      my @aGroupList = ();
      my $sSkipPrint = 0;
      foreach my $sGroup (sort(keys(%hGroupMap)))
      {
        my (%hMembers, %hResolverArgs);
        %hResolverArgs =
        (
          'ForwardMap'     => {}, # Not needed/used for this application.
          'GroupMap'       => \%hGroupMap,
          'NoRecursion'    => 0, # Always recurse for this application.
          'QueueMap'       => \%hMembers,
          'QueueList'      => "%$sGroup",
          'RecursionStack' => [],
        );
        if (!JqdResolveQueueList(\%hResolverArgs))
        {
          print STDERR "$$phProperties{'Program'}: IncludeList='$$phProperties{'IncludeList'}' Error='$hResolverArgs{'Error'}'\n";
          $sSkipPrint = 1;
          last;
        }
        if (exists($hMembers{$sMember}) && defined($hMembers{$sMember}))
	{
	  push(@aGroupList, $sGroup);
	}
      }
      unless ($sSkipPrint)
      {
        if (scalar(@aGroupList) > 0)
        {
          print "$sMember|", join(',', @aGroupList), "\n";
        }
        else
        {
          print STDERR "$$phProperties{'Program'}: Warning='Member ($sMember) does not exist in any group.'\n";
        }
      }
    }
  }
  else
  {
    foreach my $sGroup (sort(keys(%hGroupMap)))
    {
      print "$sGroup\n";
    }
  }

  ####################################################################
  #
  # Shutdown and go home.
  #
  ####################################################################

  1;


######################################################################
#
# Usage
#
######################################################################

sub Usage
{
  my ($sProgram) = @_;
  print STDERR "\n";
  print STDERR "Usage: $sProgram [-G group-file] [member ...]\n";
  print STDERR "\n";
  exit(1);
}


=pod

=head1 NAME

webjob-jqd-list-groups - List currently defined groups.

=head1 SYNOPSIS

B<webjob-jqd-list-groups> B<[-G group-file]> B<[member ...]>

=head1 DESCRIPTION

This utility lists the currently defined groups.  If one or more
members are specified, then each member is listed on a single line
followed by a comma separated list of groups as shown below.

  member_1|group_1,group_2,...
  member_2|group_1,group_2,...
  ...

=head1 OPTIONS

=over 4

=item B<-G group-file>

Specifies an alternate group file.  The default group file is
/var/webjob/config/jqd/groups.

=back

=head1 AUTHOR

Klayton Monroe

=head1 SEE ALSO

webjob-jqd-create-group(1), webjob-jqd-delete-group(1), webjob-jqd-list-group-members(1), webjob-jqd-update-group(1)

=head1 LICENSE

All documentation and code are distributed under same terms and
conditions as B<WebJob>.

=cut
