#!/usr/bin/perl -w
# Convert global scrips to per-queue scrips

use strict;
use lib "/opt/rt/rt/local/lib";
use lib "/opt/rt/rt/lib";
use lib "/opt/rt/rt/etc";
use RT;
use RT::Interface::CLI qw( CleanEnv GetCurrentUser );
use RT::User;

# Disable STDOUT buffering
$| = 1;

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

my $code;
my $msg;
my @queues_blacklist = qw(___Approvals);

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

# Get the current user all loaded
our $CurrentUser = GetCurrentUser();

unless( $CurrentUser->Id )
{
	print STDERR "No RT user found. Please consult your RT administrator.\n";
	exit 1;
}

# Get queues
my @queues;
my $QueuesObj = RT::Queues->new($CurrentUser);
$QueuesObj->UnLimit();
while ( my $queue = $QueuesObj->Next )
{
	next if (grep {$queue->Name eq $_} @queues_blacklist);
	push @queues, $queue->id;
}

my $Scrips = RT::Scrips->new($CurrentUser);
$Scrips->LimitToGlobal();
while ( my $scrip = $Scrips->Next )
{
	next if (($scrip->Id != 3) && ($scrip->Id != 6));
	my $scrip_full_description = $scrip->ConditionObj->Name." ".$scrip->ActionObj->Name." with template ".$scrip->TemplateObj->Name;
	foreach my $queue (@queues)
	{
		print "Create scrip ".$scrip->id." (".$scrip_full_description.") for queue ".$queue."\n";
		my $queue_scrip = RT::Scrip->new($CurrentUser);
		($code,$msg) = $queue_scrip->Create(
			Queue                  => $queue,
			ScripAction            => $scrip->ScripAction,
			ScripCondition         => $scrip->ScripCondition,
			Template               => $scrip->Template,
			Description            => $scrip->Description,
			CustomPrepareCode      => $scrip->CustomPrepareCode,
			CustomCommitCode       => $scrip->CustomCommitCode,
			CustomIsApplicableCode => $scrip->CustomIsApplicableCode,
	        );
		if (!$code) {
			warn "Error creating scrip: $msg\n";
			warn "Skipping global scrip deletion\n";
			next;
		}
	}
	print "Delete Global scrip ".$scrip->id."(".$scrip_full_description.")\n";
	($code,$msg) = $scrip->Delete;
	warn "Unable to delete scrip: $msg\n" if (!$code);
}
