#!/usr/bin/perl -w
######################################################################
#
# $Id: webjob-cfg-delete-list,v 1.13 2012/01/07 08:01:15 mavrik Exp $
#
######################################################################
#
# Copyright 2009-2012 The WebJob Project, All Rights Reserved.
#
######################################################################
#
# Purpose: Delete one or more KVP lists.
#
######################################################################

use strict;
use File::Basename;
use File::Path;
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 Getopt::Std;
use WebJob::KvpRoutines 1.029;
use WebJob::Properties;

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();

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

  ####################################################################
  #
  # A Delimiter, '-d', optional.
  #
  ####################################################################

  $$phProperties{'Delimiter'} = (exists($hOptions{'d'})) ? $hOptions{'d'} : ",";

  if ($$phProperties{'Delimiter'} !~ /^[ ,:;|]$/)
  {
    print STDERR "$$phProperties{'Program'}: Error='Invalid delimiter ($$phProperties{'Delimiter'}).'\n";
    exit(2);
  }

  ####################################################################
  #
  # A config file, '-f', is require.
  #
  ####################################################################

  $$phProperties{'ConfigFile'} = (exists($hOptions{'f'})) ? $hOptions{'f'} : undef;

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

  ####################################################################
  #
  # A type, '-t', is optional.
  #
  ####################################################################

  my ($sKeyRegex, $sListRegex, $sValueRegex);

  $$phProperties{'Type'} = (exists($hOptions{'t'})) ? $hOptions{'t'} : "Generic";

  if ($$phProperties{'Type'} =~ /^Generic$/i)
  {
    $sKeyRegex = qq([\\w.-]+);
    $sValueRegex = qq([^$$phProperties{'Delimiter'}]*);
  }
  elsif ($$phProperties{'Type'} =~ /^ClientAcl$/i)
  {
    $sKeyRegex = $$phProperties{'CommonRegexes'}{'ClientId'};
    $sValueRegex = $$phProperties{'CommonRegexes'}{'Cidr'};
  }
  else
  {
    print STDERR "$$phProperties{'Program'}: Error='Invalid type ($$phProperties{'Type'}).'\n";
    exit(2);
  }
  $sListRegex = "(?:|$sValueRegex(?:[$$phProperties{'Delimiter'}]$sValueRegex)*)"; # Empty lists are allowed.

  ####################################################################
  #
  # If there isn't at least one argument left, it's an error.
  #
  ####################################################################

  if (scalar(@ARGV) < 1)
  {
    Usage($$phProperties{'Program'});
  }

  ####################################################################
  #
  # Validate each key.
  #
  ####################################################################

  my (%hFailKeys, %hPassKeys);

  foreach my $sKey (@ARGV)
  {
    if ($sKey =~ /^$sKeyRegex$/)
    {
      $hPassKeys{$sKey}++;
    }
    else
    {
      $hFailKeys{$sKey}++;
    }
  }

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

  ####################################################################
  #
  # Conditionally create a lock file. This is an exclusive lock.
  #
  ####################################################################

  my (%hLockArgs);

  if ($$phProperties{'ConfigFile'} ne "-")
  {
    %hLockArgs =
    (
      'LockFile'   => $$phProperties{'ConfigFile'} . ".lock",
      'LockRemove' => 1,
    );
    if (!KvpLockFile(\%hLockArgs))
    {
      print STDERR "$$phProperties{'Program'}: Error='$hLockArgs{'Error'}'\n";
      exit(2);
    }
  }

  ####################################################################
  #
  # Create KVP map.
  #
  ####################################################################

  my (%hKvpMap) = ();

  if (-f $$phProperties{'ConfigFile'} || $$phProperties{'ConfigFile'} eq "-")
  {
    my %hLArgs =
    (
      'File'           => $$phProperties{'ConfigFile'},
      'Properties'     => \%hKvpMap,
      'Template'       => { $sKeyRegex => $sListRegex, },
      'VerifyValues'   => 1,
    );
    if (!KvpGetKvps(\%hLArgs))
    {
      print STDERR "$$phProperties{'Program'}: Error='$hLArgs{'Error'}'\n";
      exit(2);
    }
  }
  else
  {
    print STDERR "$$phProperties{'Program'}: Error='File ($$phProperties{'ConfigFile'}) does not exist or is not regular.'\n";
    exit(2);
  }

  ####################################################################
  #
  # Remove each entry in the specified list.
  #
  ####################################################################

  foreach my $sKey (@ARGV)
  {
    delete($hKvpMap{$sKey});
  }

  ####################################################################
  #
  # Write the new config file.
  #
  ####################################################################

  my %hLArgs =
  (
    'File'           => $$phProperties{'ConfigFile'},
    'Properties'     => \%hKvpMap,
    'Template'       => { $sKeyRegex => $sListRegex, },
    'VerifyValues'   => 0,
  );
  if (!KvpSetKvps(\%hLArgs))
  {
    print STDERR "$$phProperties{'Program'}: Error='$hLArgs{'Error'}'\n";
    exit(2);
  }

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

  if ($$phProperties{'ConfigFile'} ne "-")
  {
    KvpUnlockFile(\%hLockArgs);
  }

  1;


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

sub Usage
{
  my ($sProgram) = @_;
  print STDERR "\n";
  print STDERR "Usage: $sProgram [-d delimiter] [-t type] -f {file|-} [key [key ...]]\n";
  print STDERR "\n";
  exit(1);
}


=pod

=head1 NAME

webjob-cfg-delete-list - Delete one or more KVP lists.

=head1 SYNOPSIS

B<webjob-cfg-delete-list> B<[-d delimiter]> B<[-t type]> B<-f {file|-}> B<[key [key ...]]>

=head1 DESCRIPTION

This utility deletes one or more KVP (Key/Value Pair) lists.

=head1 OPTIONS

=over 4

=item B<-d delimiter>

Specifies the list delimiter.  Valid delimiters include the following
characters: space ' ', comma ',', colon ':', semi-colon ';', and pipe
'|'.  The default delimiter is a comma.  Note that parse errors are
likely to occur if the specified delimiter appears in any of the
values.

=item B<-f {file|-}>

Specifies the config file to operate on.

=item B<-t type>

Specifies the type of config file being operated on.  Each supported
type has a custom template that is used to validate keys and values.
Currently, the following types are supported: ClientAcl and Generic.
The default type is Generic.

=back

=head1 AUTHOR

Klayton Monroe

=head1 SEE ALSO

webjob-cfg-create-list(1), webjob-cfg-update-list(1)

=head1 LICENSE

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

=cut
