+delete $feed->{entry};
+warn "# feed without entry ",dump( $feed );
+
+if ( my @next = map { $_->{href} } grep { $_->{rel} eq 'next' && $_->{type} eq 'application/atom+xml' } @{ $feed->{link} } ) {
+ warn "## next ",dump(@next);
+ $url = $next[0];
+ goto restart;
+}
+
+skip_url:
+
+if ( $url = shift @urls ) {
+ warn "## next url $url";
+ goto restart;
+}
+
+warn "# tree ",dump( $tree );
+
+warn "# ticket_items ",dump( $ticket_items );
+
+
+my $rt = RT::Client::REST->new(
+ server => 'http://rt.rot13.org/rt',
+ timeout => 30,
+);
+
+$rt->login(username => $ENV{RT_USER}, password => $ENV{RT_PASSWORD});
+
+foreach my $nr ( keys %$ticket_items ) {
+
+ my $ticket = eval { $rt->show(type => 'ticket', id => $nr) };
+ warn "# ticket $nr ",dump($ticket);
+
+ next unless $ticket;
+
+ $ticket->{zotero_items} = $ticket_items->{$nr};
+
+ my $modified = $db->modify( "rt/$nr" => sub {
+ my $doc = shift;
+ $doc->{$_} = $ticket->{$_} foreach keys %$ticket;
+ return $doc;
+ });
+
+ warn "# modified ",dump($modified);
+
+ # copy attachments to CouchDB (they never change, so do it just once
+ if ( my @attachment_ids = $rt->get_attachment_ids( id => $nr ) ) {
+
+ warn "# get_attachment_ids = ",dump( @attachment_ids );
+ my $doc = $db->get("rt/$nr");
+ my @attachments;
+
+ foreach my $attachment_id ( @attachment_ids ) {
+ my $attachment = $rt->get_attachment( parent_id => $nr, id => $attachment_id );
+ if ( $attachment->{Filename} && $attachment->{ContentEncoding} eq 'base64' ) {
+ #$attachment->{Filename} ||= $attachment_id;
+ my $content = delete $attachment->{Content};
+ if ( ! exists $doc->{_attachments}->{ $attachment->{Filename} } ) {
+ utf8::encode($content) || warn "utf8::encode error!";
+ warn "# extracted ",length( $content ), " bytes";
+ warn "## attachment ",dump( $attachment );
+ my $url = sprintf 'rt/%d/%s?rev=%s', $nr, uri_escape($attachment->{Filename}), $modified->{rev};
+# $modified = $db->request( PUT => $url, $content, $attachment->{ContentType} );
+ }
+ }
+ push @attachments, $attachment;
+ }
+
+
+ $db->modify( "rt/$nr" => sub {
+ my $doc = shift;
+ $doc->{attachments} = [ @attachments ];
+ warn "## attachments on $nr = ", $#attachments + 1;
+ return $doc;
+ }) if @attachments;
+
+ }
+
+ if ( $ticket->{Queue} !~ m/ILL/i ) {
+ warn "SKIP $ticket not in ILL queue!";
+ next;
+ }
+
+ foreach my $id ( @{ $ticket_items->{$nr} } ) {
+ warn "# item $id ",dump( $items->{$id} );
+
+# $rt->comment( ticket_id => $nr, message => dump( $items->{$id} ) );
+
+ }
+
+}