#!/usr/bin/perl
# Copyright © 2020, Bradley M. Kuhn
#   License: AGPL-3.0-or-later
# probably want to pipe in: rt ls -i "Status = 'needs-release-approval'" | xargs -I_ rt show -f DependsOn _/links | grep -Eo '[0-9]+,?' | sed -e 's/,$//'

use strict;
use warnings;

use autodie qw(:all);
my $RT_CMD = '/usr/bin/rt';

my($queue, $oldUser, $newUser) = @ARGV;

my $count = 0;
foreach my $id (<STDIN>) {
  chomp $id;
  my $line;
  open(my $rtShowFH, "-|", "$RT_CMD", "show", '-t', 'ticket', '-f', 'Queue,id,status,owner', $id);
  my %tixData;
  while (my $line = <$rtShowFH>) {
    die "$id: invalid line: $line" unless $line =~ /^(\S+)\s*:\s+(\S+)\s*$/;
    $tixData{$1} = $2;
  }
  close $rtShowFH;

  die "$tixData{id} is not $id" unless $tixData{id} =~ /$id/;
  die "$id: missing status or Owner" unless defined  $tixData{Status} and defined $tixData{Owner};

  my $skip = 0;
  if ($tixData{Queue} ne $queue) {
    $skip++; print STDERR "$id: skipping since status $tixData{Queue}\n";
  } elsif ($tixData{Status} ne 'open') {
    $skip++; print STDERR "$id: skipping since status $tixData{Status} is not open\n"
  } elsif ($tixData{Owner} ne $oldUser) {
    $skip++; print STDERR "$id: skipping since status $tixData{Owner} is not $oldUser\n" unless $tixData{Owner} eq $oldUser;
  }
  next if $skip > 0;
  print STDERR "$id: reassigning to $newUser\n";
  system($RT_CMD, 'edit', $id, 'set', "Owner=$newUser");
  $count++;
}

print "Reassigned $count tickets to $newUser from $oldUser\n";