#!/usr/local/bin/perl -w

# RT3 escalation script
#
# This script escalates tickets priorties using the inbuilt RT code.
#
# Tweaked version of RT2 script by T.D.Bishop@kent.ac.uk, July 2003.
# Update for multiple queues, March 2004.
#
# $Id: rt-escalate,v 1.3 2005/06/21 13:25:10 tdb Exp $

### Configuration

my(@queues); # do not delete this

# Queues to operate on (default is all)
#@queues = qw ( queue1 queue2 );

# Location of RT3's libs
use lib ("/usr/local/packages/rt/lib", "/usr/local/packages/rt/local/lib");

### Code

use strict;
use Carp;

# Pull in the RT stuff
package RT;
use RT::Interface::CLI qw(CleanEnv GetCurrentUser GetMessageContent loc);

# Clean our the environment
CleanEnv();

# Load the RT configuration
RT::LoadConfig();

# Initialise RT
RT::Init();

# Drop any setgid permissions we might have
#RT::DropSetGIDPermissions();

use RT::Date;
use RT::Tickets;
use RT::Action::EscalatePriority;

if(!@queues) {
    my $queues = new RT::Queues($RT::SystemUser);
    $queues->LimitToEnabled();
    foreach my $queue (@{$queues->ItemsArrayRef()}) {
        push @queues, $queue->Name;
    }
}

foreach my $queuename (@queues) {
    # Load in the queue
    my $queue = new RT::Queue($RT::SystemUser);
    $queue->Load($queuename);

    my $now = new RT::Date($RT::SystemUser);
    $now->SetToNow();

    # Get hold of new and open tickets only
    my $tickets = new RT::Tickets($RT::SystemUser);
    $tickets->LimitStatus(VALUE => 'open');
    $tickets->LimitStatus(VALUE => 'new');
    $tickets->LimitQueue(VALUE => $queue->Id);

    # Process each ticket
    while (my $ticket = $tickets->Next) {
        my $action = new RT::Action::EscalatePriority(
            TicketObj => $ticket,
            CurrentUser => $RT::SystemUser
        );
        if ($action->Prepare()) {
            $action->Commit();
        }
    }
}

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