#!/usr/bin/perl -w
######################################################################
#
# $Id: webjob-jqd-create-group,v 1.15 2012/01/07 08:01:18 mavrik Exp $
#
######################################################################
#
# Copyright 2007-2012 The WebJob Project, All Rights Reserved.
#
######################################################################
#
# Purpose: Create a new group.
#
######################################################################

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:g:', \%hOptions))
  {
    Usage($$phProperties{'Program'});
  }

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

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

  ####################################################################
  #
  # A group, '-g', is required.
  #
  ####################################################################

  $$phProperties{'Group'} = (exists($hOptions{'g'})) ? $hOptions{'g'} : undef;

  if (!defined($$phProperties{'Group'}))
  {
    Usage($$phProperties{'Program'});
  }

  if ($$phProperties{'Group'} !~ /^$$phProperties{'CommonRegexes'}{'Group'}$/)
  {
    print STDERR "$$phProperties{'Program'}: Error='The group ($$phProperties{'Group'}) does not pass muster.'\n";
    exit(2);
  }

  ####################################################################
  #
  # Validate each member.
  #
  ####################################################################

  my (%hFailMembers, %hPassMembers);

  foreach my $sMember (@ARGV)
  {
    my $sMemberRegex = "(?:" . $$phProperties{'CommonRegexes'}{'GroupToken'} . "|" . $$phProperties{'CommonRegexes'}{'ClientId'} . ")";
    if ($sMember =~ /^$sMemberRegex$/)
    {
      $hPassMembers{$sMember}++;
    }
    else
    {
      $hFailMembers{$sMember}++;
    }
  }

  if (%hFailMembers)
  {
    print STDERR "$$phProperties{'Program'}: Error='One or more members (" . join(",", sort(keys(%hFailMembers))) . ") do not pass muster.'\n";
    exit(2);
  }

  ####################################################################
  #
  # Create group 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);
  }

  ####################################################################
  #
  # Make sure that the specified group does not exist.
  #
  ####################################################################

  if (exists($hGroupMap{$$phProperties{'Group'}}))
  {
    print STDERR "$$phProperties{'Program'}: Error='Group ($$phProperties{'Group'}) already exists.'\n";
    exit(2);
  }

  ####################################################################
  #
  # Make sure that any groups in the member list exist.
  #
  ####################################################################

  foreach my $sMember (keys(%hPassMembers))
  {
    if ($sMember =~ /^%(.+)/ && !exists($hGroupMap{$1}))
    {
      $hFailMembers{$sMember}++;
    }
  }

  if (%hFailMembers)
  {
    print STDERR "$$phProperties{'Program'}: Error='One or more members (" . join(",", sort(keys(%hFailMembers))) . ") represent groups that do not exist.'\n";
    exit(2);
  }

  ####################################################################
  #
  # Build the specified group.
  #
  ####################################################################

  $hGroupMap{$$phProperties{'Group'}} = join(",", sort(keys(%hPassMembers)));

  ####################################################################
  #
  # Write the new group file.
  #
  ####################################################################

  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'   => 0,
  );
  if (!KvpSetKvps(\%hLArgs))
  {
    print STDERR "$$phProperties{'Program'}: Error='$hLArgs{'Error'}'\n";
    exit(2);
  }

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

  1;


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

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


=pod

=head1 NAME

webjob-jqd-create-group - Create a new group.

=head1 SYNOPSIS

B<webjob-jqd-create-group> B<[-G group-file]> B<-g group> B<[member [member ...]]>

=head1 DESCRIPTION

This utility creates a new group having zero or more members.
Duplicate members (if any) are automatically squashed.

=head1 OPTIONS

=over 4

=item B<-G group-file>

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

=item B<-g group>

Specifies the name of the group to create.

=back

=head1 AUTHOR

Klayton Monroe

=head1 SEE ALSO

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

=head1 LICENSE

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

=cut
