#!/usr/bin/perl

use Error qw(:try);
use RT::Client::REST;

$directoryname = '/tmp/rt-export-test';
unless (-d $directoryname) {
	print "$directoryname is not a directory.\n";
	exit(1);
} 

my $rt = RT::Client::REST->new(
  server => 'http://rt',
  timeout => 30,
);
my $user = 'root';
my $pass = 'password';

try {
  $rt->login(username => $user, password => $pass);
} catch Exception::Class::Base with {
  die "problem logging in: ", shift->message;
};

# Get the tickets
my @ids = $rt->search(
  type => 'ticket',
  query => "%",
  orderby => '+id'
);

for my $id (@ids) {

  open (TIX, ">${directoryname}/${id}.txt");	  
  my ($ticket) = $rt->show(type => 'ticket', id => $id);
  print TIX "Ticket: $id";
  print TIX "\nSubject: ";
  print TIX $ticket->{Subject};
  print TIX "\nContent Follows\n";
    
  my @attachments = $rt->get_attachment_ids(id => $id);
  for my $attachid (@attachments) {
    my $attachment = $rt->get_attachment(parent_id => $id, id => $attachid);
    if($attachment->{ContentType} eq "text/plain"){
      print TIX $attachment->{Content};
    } elsif ($attachment->{ContentType} eq "multipart/mixed"){
      print TIX $attachment->{Content};
    } else {
      mkdir "${directoryname}/${id}";
      open (ATTACH, ">${directoryname}/${id}/$attachment->{Filename}");
      print ATTACH $attachment->{Content};
      close (ATTACH);
    }
  } 
  close (TIX); 
}

1;
