#!/usr/bin/perl

# Copyright (C) 2002 Northern Principle Limited 
# Version 1.0: 27/8/2002 Robie Basak <robie@principle.co.uk>
# $Id: rt-autostart,v 1.1 2002/08/27 15:47:17 cvs Exp $

# This is rt-autostart; run it from cron periodically to automatically unstall
# tickets which need to be started in the future (to mark a ticket as such, set
# the start date to a date in the future, then mark it as stalled). The program
# needs to be sgid rt, the same as the main rt program.

# This program actually just opens tickets which match all of the following:
#   1) status is 'stalled'
#   2) start date is greater than the current date
#   3) last transaction was before the start date.

# This does mean that if the ticket has a transaction after the start date,
# then it is left alone, because it is assumed that you've seen it and want to
# keep it stalled.

# There was a bug in RT 2.0.14 and earlier which prevented this from working;
# so either use a later version which has the bug fixed, or apply my patch
# first (search the rt-dev archive for a subject of "[patch]
# RT::Tickets->LimitDate", I can't give a reference because I've yet to
# actually post it :)


# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

use strict;

use lib "/usr/local/rt2/lib";
use lib "/usr/local/rt2/etc";

use RT::Date;
use RT::Interface::CLI qw(CleanEnv LoadConfig DBConnect);
use RT::Tickets;

CleanEnv();
LoadConfig();
DBConnect();

my $date = new RT::Date or die;
$date->SetToNow() or die;
my $iso = $date->ISO() or die;

my $unsetdate = new RT::Date or die;
$unsetdate->Set(Format => 'unix', Value => 0) or die;
my $unsetiso = $unsetdate->ISO() or die;


my $tickets = new RT::Tickets(RT::SystemUser) or die;
$tickets->LimitStatus(VALUE => 'stalled', OPERATOR => '=') or die;
$tickets->LimitDate(FIELD => 'Starts', OPERATOR => '>', VALUE => $unsetiso);
$tickets->LimitDate(FIELD => 'Starts', OPERATOR => '>',
		    VALUE => 'main.LastUpdated', QUOTEVALUE => 0) or die;
$tickets->LimitDate(FIELD => 'Starts', OPERATOR => '<', VALUE => $iso) or die;

while(my $ticket = $tickets->Next()) {
	$ticket->Open;
}
