#!/usr/bin/perl
#
# RT ticket counter
#
# This script counts tickets.
#
# Configuration settings are read from /etc/sysconfig/$scriptname (see definition, below)
#
# TODO:
# + set value of $pkgname from spec file ('sed')
#

use strict;
use warnings;


sub English_Month_to_Text {

   # Yes, there are better ways of doing this, but we need to sidestep locales
   my $month = shift;

   if    ($month == 1)  { return "JAN" }
   elsif ($month == 2)  { return "FEB" }
   elsif ($month == 3)  { return "MAR" }
   elsif ($month == 4)  { return "APR" }
   elsif ($month == 5)  { return "MAY" }
   elsif ($month == 6)  { return "JUN" }
   elsif ($month == 7)  { return "JUL" }
   elsif ($month == 8)  { return "AUG" }
   elsif ($month == 9)  { return "SEP" }
   elsif ($month == 10) { return "OCT" }
   elsif ($month == 11) { return "NOV" }
   elsif ($month == 12) { return "DEC" }
   
   return "ERR";
}

sub Date_to_English_String {
   my @recvdate = @_;

   return $recvdate[0] . "-" . English_Month_to_Text($recvdate[1]) .  "-" . $recvdate[2];
}


# *** BEGIN: RT initialization ***
use RT;
use RT::Date;
use RT::Tickets;

my $SystemUser;
my $sendmail;

BEGIN {
    RT->LoadConfig;
    RT->Init;
    # Become RT System User
    $SystemUser = RT::CurrentUser->new;
    $SystemUser->Load('root');
    die "Could not become root" unless $SystemUser;
    $sendmail = RT->Config->Get('SendmailPath') . " " . RT->Config->Get('SendmailArguments');
}
# *** END: RT initialization ***




# *** BEGIN: process command-line options ***
use Getopt::Long;
my $debug=0;
my $help=0;
my $myweek;
Getopt::Long::Configure('bundling');
Getopt::Long::GetOptions(
  "d|debug"       => \$debug,
  "h|help"        => \$help,
  "w|week=i"      => \$myweek,
) or Pod::Usage::pod2usage(2);

use Pod::Usage;
Pod::Usage::pod2usage(
    -exitstatus => 0,
    -verbose    => 2,    # 2 to print full pod
) if $help;
# *** END: process command-line options ***




# *** BEGIN: Load configuration from /etc/sysconfig
use Config::Simple;
my $pkgname = "perl-RT-admin-tools";

# silently set sane defaults if no configuration file can be found
my $recipient  = "root\@localhost";   # where to send mail to
my $sender  = "root\@localhost";      # whence the mail cometh
my @queues = ();                     # which queues to count

# tell Config::Simple about our config file
Config::Simple->import_from("/etc/sysconfig/$pkgname", \my %Config);

# overwrite the sane defaults if import_from successful
$recipient = $Config{'default.RECIPIENT'}      if (defined $Config{'default.RECIPIENT'});
$sender = $Config{'default.SENDER'}            if (defined $Config{'default.SENDER'});
@queues = split ' ', $Config{'default.QUEUES'} if (defined $Config{'default.QUEUES'});

if ($debug) {
   print "RECIPIENT: $recipient\n";
   print "SENDER: $sender\n";
   print "QUEUES: @queues\n";
}
# *** END: Load configuration from /etc/sysconfig



# *** BEGIN: figure out the dates ***
use Date::Calc;

# Date::Calc represents a date as an array of integers ( YYYY, MM, DD )
my ($year, $month, $day);
my $week;
my (@monday, @span_beg, @span_end); 

if ((defined($myweek)) && ("$myweek" ne "")) {
   # --week option given: calculate begin and end days
   $year = Date::Calc::This_Year();
   $week = $myweek;
   @monday = Date::Calc::Monday_of_Week($week, $year);
   @span_beg = Date::Calc::Add_Delta_Days(@monday, -1);
   @span_end = Date::Calc::Add_Delta_Days(@monday, +5);
} else {
   # no --week option: "now minus 7" until now
   ( $week, $year ) = Date::Calc::Week_of_Year( Date::Calc::Today() );
   @span_end = Date::Calc::Today_and_Now();
   @span_beg = Date::Calc::Add_Delta_DHMS(@span_end, -7, 0, 0, 0);
}
# *** END: figure out the dates ***



# *** BEGIN: query queues ***
my $overall_count=0;
my $queue_msg="";

foreach my $queue (@queues) {
   my $tsql;
   my $queue_count=0;
   my $my_msg;
   my $tickets = RT::Tickets->new($RT::SystemUser);
   if ((defined($myweek)) && ("$myweek" ne "")) {
      $tsql="Resolved <= '$span_end[0]-$span_end[1]-$span_end[2]' AND Resolved >= '$span_beg[0]-$span_beg[1]-$span_beg[2]' AND (Queue = '$queue')";
   } else {
      $tsql="Resolved > '7 days ago' AND (Queue = '$queue')";
   }
   print "TSQL query: $tsql\n" if ($debug);
   $tickets->FromSQL($tsql);
   while (my $t = $tickets->Next) {
      $queue_count++;
      # do stuff with each ticket $t here
      $my_msg .= "  #".$t->id." :";
      $my_msg .=  " ".$t->Subject;
      if ($debug) {
         my $resolved_date = $t->ResolvedObj;
         $my_msg .= " (Resolved on " . $resolved_date->Get . ")";
      }
      $my_msg .= "\n";
   }
   if ( $queue_count gt 0 ) {
      $queue_msg .= "Resolved tickets in queue $queue for week $week:\n";
      $queue_msg .= $my_msg;
      $queue_msg .= "  [Summary $queue: $queue_count]\n\n";
   }
   $overall_count=$overall_count+$queue_count;
}

if ($queue_msg eq "") {
   $queue_msg = "* NONE\n";
}
# *** END: query queues ***



# *** BEGIN: construct message ***
my $charset = "UTF-8";  # charset to use in emails
my $span_begstr = Date_to_English_String(@span_beg[0..2]);
my $span_endstr = Date_to_English_String(@span_end[0..2]);

my $msg_begin = <<EOF;
Content-Type: text/plain; charset="$charset"
From: $sender
To: $recipient
Subject: RT ticket counts week $week : * $overall_count RT Tickets resolved

EOF

my $msg_middle;
if ((defined($myweek)) && ("$myweek" ne "")) {
   $msg_middle = "Note: checked tickets between $span_begstr and $span_endstr.\n";
} else {
   $span_endstr .= sprintf(" %02d:%02d:%02d", $span_end[3], $span_end[4], $span_end[5]);
   $msg_middle = "Note: checked tickets in 7-day period ending $span_endstr.\n";
}

my $msg_end = <<EOF;

* $overall_count RT Tickets resolved

Details:

$queue_msg
 Have a lot of fun!
EOF

my $msg = $msg_begin . $msg_middle . $msg_end;

# *** END: construct message ***



# *** BEGIN: send message ***
if (! $debug){
# Send the message
	open(SENDMAIL, "|$sendmail") || die "Error sending mail: $!";
	print SENDMAIL $msg;
	close(SENDMAIL);
}
else {
	print "week $week : $span_begstr until $span_endstr\n";
	print "$msg\n";
}
# *** END: send message ***



# Disconnect before we finish off
$RT::Handle->Disconnect();
exit 0;


__END__

=head1 rt-queue-count

rt-queue-count counts resolved RT tickets by queue

=head1 SYNOPSIS

./rt-queue-count [OPTIONS]

 Options:
    -w <int>         | --week <int>
    -h               | --help
    -d               | --debug

=head1 COMMAND LINE OPTIONS

=over 8

=item B<--week> F<int>

Instead of using the current week, use week number F<int>.

=item B<--help>

Produces this output.

=item B<--debug>

Print debug output on STDOUT.

=back

=head1 CONFIGURATION

This script is designed to be run on a machine with an active RT instance,
otherwise it will not work!

Also, for this script to do anything useful, reasonable values for
SENDER, RECIPIENT, and QUEUES should be defined in the configuration
file /etc/sysconfig/perl-RT-admin-tools

See the comments embedded in that file for more information.

=head1 AUTHORS

Originally written by Lars Vogdt <lrupp@suse.de>

Updated and packaged by Nathan Cutler <ncutler@suse.cz>

=head1 SUPPORT

Please use https://bugzilla.novell.com to submit patches or suggest improvements.

Include package name and version information with all correspondence (when possible use output from
'zypper if').

