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

# RT3 auto close script
#
# This script automatically closes any tickets that have been in the
# autoclose status for more than a specific period.
#
# Written by T.D.Bishop@kent.ac.uk, January 2008.
#
# $Id: rt-autoclose,v 1.2 2008/07/17 14:59:28 tdb Exp $

### Configuration

# Resolve when older than 3 days
# (how long, in seconds, after LastUpdated has changed)
my $resolve_at_age = 3 * 24 * 60 * 60;

my @queues; # do not delete this

# Queues to operate on
#@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::Queue;
use RT::Queues;
use RT::Tickets;

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

    # Date object used for diffing
    my $now = new RT::Date($RT::SystemUser);
    $now->SetToNow();

    # Get hold of tickets in autoclose state in this queue
    my $tickets = new RT::Tickets($RT::SystemUser);
    $tickets->LimitStatus(VALUE => 'autoclose');
    $tickets->LimitQueue(VALUE => $queue->Id);

    # Process each ticket
    while (my $ticket = $tickets->Next) {
        # Reset "now" since the search probably took a while
        $now->SetToNow();
        # How long ago was the ticket last updated?
        my $diff = $now->Diff($ticket->LastUpdatedObj());
        # If it's older than our resolve age, resolve it
        if (defined $diff && $diff > $resolve_at_age) {
            $ticket->SetStatus('resolved');
        }
    }
}

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