#!/usr/bin/perl -w
######################################################################
#
# $Id: webjob-jqd-delete-queue,v 1.11 2012/01/07 08:01:19 mavrik Exp $
#
######################################################################
#
# Copyright 2007-2012 The WebJob Project, All Rights Reserved.
#
######################################################################
#
# Purpose: Delete one or more job queues.
#
######################################################################

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

  ####################################################################
  #
  # A job queue directory, '-d', is optional.
  #
  ####################################################################

  $$phProperties{'JobQueueDirectory'} = (exists($hOptions{'d'})) ? $hOptions{'d'} : "/var/webjob/spool/jqd";

  ####################################################################
  #
  # The be quiet flag, '-q', is optional.
  #
  ####################################################################

  $$phProperties{'BeQuiet'} = (exists($hOptions{'q'})) ? 1 : 0;

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

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

  ####################################################################
  #
  # Make sure the job queue directory exists.
  #
  ####################################################################

  if (!-d $$phProperties{'JobQueueDirectory'})
  {
    print STDERR "$$phProperties{'Program'}: Error='Base directory ($$phProperties{'JobQueueDirectory'}) does not exist.'\n";
    exit(2);
  }

  ####################################################################
  #
  # Acquire the index lock. This is an exclusive lock.
  #
  ####################################################################

  my (%hIndexLockArgs);

  $$phProperties{'QueueIndex'} = $$phProperties{'JobQueueDirectory'} . "/" . "queue.index";

  %hIndexLockArgs =
  (
    'LockFile' => $$phProperties{'QueueIndex'} . ".lock",
    'LockMode' => "+<", # The file must exist or this will fail.
  );
  if (!JqdLockFile(\%hIndexLockArgs))
  {
    print STDERR "$$phProperties{'Program'}: Error='$hIndexLockArgs{'Error'}'\n";
    exit(2);
  }

  ####################################################################
  #
  # If the queue index does not exist, create it.
  #
  ####################################################################

  if (!-f $$phProperties{'QueueIndex'})
  {
    if (!open(FH, "> $$phProperties{'QueueIndex'}"))
    {
      print STDERR "$$phProperties{'Program'}: Error='File ($$phProperties{'QueueIndex'}) could not be created ($!).'\n";
      exit(2);
    }
    close(FH);
  }

  ####################################################################
  #
  # Create forward/reverse queue maps.
  #
  ####################################################################

  my (%hForwardQueueMap, %hReverseQueueMap);

  my %hQueueMapArgs =
  (
    'ForwardQueueMap'   => \%hForwardQueueMap,
    'JobQueueDirectory' => $$phProperties{'JobQueueDirectory'},
    'KeyRegex'          => "(?:" . $$phProperties{'CommonRegexes'}{'ClientId'} . "|" . $$phProperties{'CommonRegexes'}{'ClientSuppliedFilename'} . ")",
    'ReverseQueueMap'   => \%hReverseQueueMap,
    'SharedLock'        => 0, # We already have an exclusive lock.
    'ValueRegex'        => "\\d+",
  );
  if (!JqdSetupQueueMaps(\%hQueueMapArgs))
  {
    print STDERR "$$phProperties{'Program'}: Error='$hQueueMapArgs{'Error'}'\n";
    exit(2);
  }

  ####################################################################
  #
  # Attempt to delete each queue in the specified list.
  #
  ####################################################################

  my ($sIndexUpdated, $sQueueId) = (0, 0);

  foreach my $sQueue (@ARGV)
  {
    my %hLArgs =
    (
      'BeQuiet'           => $$phProperties{'BeQuiet'},
      'JobQueueDirectory' => $$phProperties{'JobQueueDirectory'},
      'Queue'             => $sQueue,
    );
    if (!JqdDeleteQueue(\%hLArgs))
    {
      print STDERR "$$phProperties{'Program'}: Error='$hLArgs{'Error'}'\n";
      last;
    }
    if (exists($hForwardQueueMap{$sQueue}))
    {
      delete($hReverseQueueMap{$hForwardQueueMap{$sQueue}});
      delete($hForwardQueueMap{$sQueue});
      $sIndexUpdated = 1;
    }
  }

  ####################################################################
  #
  # Conditionally update the queue index.
  #
  ####################################################################

  if ($sIndexUpdated)
  {
    $$phProperties{'TempQueueIndex'} = $$phProperties{'JobQueueDirectory'} . "/" . "queue.index.temp";
    if (!open(FH, "> $$phProperties{'TempQueueIndex'}"))
    {
      print STDERR "$$phProperties{'Program'}: Error='File ($$phProperties{'TempQueueIndex'}) could not be opened ($!)'\n";
      JqdUnlockFile(\%hIndexLockArgs);
      exit(2);
    }
    foreach my $sQueue (sort(keys(%hForwardQueueMap)))
    {
      print FH "$sQueue=$hForwardQueueMap{$sQueue}\n";
    }
    close(FH);
    if (!rename($$phProperties{'TempQueueIndex'}, $$phProperties{'QueueIndex'}))
    {
      print STDERR "$$phProperties{'Program'}: Error='Unable update the queue.index ($!).";
      JqdUnlockFile(\%hIndexLockArgs);
      exit(2)
    }
  }

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

  JqdUnlockFile(\%hIndexLockArgs);

  1;


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

sub Usage
{
  my ($sProgram) = @_;
  print STDERR "\n";
  print STDERR "Usage: $sProgram [-q] [-d jqd-dir] queue [queue ...]\n";
  print STDERR "\n";
  exit(1);
}


=pod

=head1 NAME

webjob-jqd-delete-queue - Delete one or more job queues.

=head1 SYNOPSIS

B<webjob-jqd-delete-queue> B<[-q]> B<[-d jqd-dir]> B<queue [queue ...]>

=head1 DESCRIPTION

This utility deletes one or more job queues.

=head1 OPTIONS

=over 4

=item B<-d jqd-dir>

Specifies the base directory where queues are to be deleted. This
directory must exist. The default value is /var/webjob/spool/jqd.

=item B<-q>

Be quiet (i.e., only report errors) while executing.

=back

=head1 AUTHOR

Klayton Monroe

=head1 SEE ALSO

webjob-jqd-create-queue(1)

=head1 LICENSE

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

=cut
