#!/usr/bin/perl -w
# AS RT 4.2 can apply a scrip to more than one queue, try to remove duplicate scrips and apply existing ones to the needed queues

use strict;
use lib "/appli/rt-4.2.3/rt/local/lib";
use lib "/appli/rt-4.2.3/rt/lib";
use lib "/appli/rt-4.2.3/rt/etc";
use RT;
use RT::Interface::CLI qw( CleanEnv GetCurrentUser );
use RT::User;
use Digest::MD5 qw(md5);

# Disable STDOUT buffering
$| = 1;

# Set locales
$ENV{'LANG'} = 'POSIX';
$ENV{'LC_ALL'} = 'POSIX';

my $val;
my $msg;

# RT CLI initialization
CleanEnv();
RT::LoadConfig();
RT::Init();

my %scrips;
my $Scrips = RT::Scrips->new( $RT::SystemUser );
$Scrips->UnLimit;
$Scrips->OrderBy(FIELD => 'id', ORDER => 'ASC');

while (my $Scrip = $Scrips->Next) {
	if ( $Scrip->IsGlobal ) {
		print "Skiping scrip ".$Scrip->id.", global\n";
		next;
	}
	my @datas;
	foreach my $method(qw(Description ScripCondition ScripAction CustomIsApplicableCode CustomPrepareCode CustomCommitCode Disabled Template)) {
		push @datas, $Scrip->$method || '';
	}
	
	my $signature = md5(join('', @datas));
	my $ObjectScrips = RT::ObjectScrips->new( $RT::SystemUser );
    	$ObjectScrips->LimitToScrip( $Scrip->id );
	if ( $ObjectScrips->Count == 0 ) {
		print "Skiping scrip ".$Scrip->id.", not applied\n";
		next;
	}
	if ( $scrips{$signature} ) {
		print "Scrip ".$Scrip->id." already seen as ".$scrips{$signature}{id}."\n";
		while (my $ObjectScrip = $ObjectScrips->Next) {
			my $object_id = $ObjectScrip->ObjectId;
			my $stage = $ObjectScrip->Stage;
			push @{$scrips{$signature}{to_apply}}, {ObjectId => $object_id, Stage => $stage};
		}
		push @{$scrips{$signature}{to_delete}}, $Scrip->id;
	} else {
		$scrips{$signature}{id} = $Scrip->id;
	}
}

foreach my $signature (keys %scrips) {
	next unless ( $scrips{$signature}{to_apply} );
	my $Scrip = RT::Scrip->new( $RT::SystemUser );
	$Scrip->Load($scrips{$signature}{id});
	print "Apply $scrips{$signature}{id} to queues ".join(',', map {$_->{ObjectId}} @{$scrips{$signature}{to_apply}} )."\n";
	foreach my $queue (@{$scrips{$signature}{to_apply}} ) {
		my ($val, $msg) = $Scrip->AddToObject( ObjectId => $queue->{ObjectId}, Stage => $queue->{Stage} );
		unless ( $val ) {
			die "$msg\n";
		} 
	}
	print "Delete ".join(',', @{$scrips{$signature}{to_delete}})."\n";
	foreach my $scrip_id (@{$scrips{$signature}{to_delete}}) {
		my $ObsoletScrip = RT::Scrip->new( $RT::SystemUser );
		$ObsoletScrip->Load($scrip_id);
		my ($val, $msg) = $ObsoletScrip->Delete;
		die "$msg\n" unless ($val);
	}
}

