#!/usr/bin/perl
# getBibTeXFromZoteroCollection - get a bibtex file with all references from a particular
#                                 collection in Zotero using MozRepl
# Specify the id of the collection in the line "var collection = collections[2]"
# (e.g. 2 corresponds to the third collection)
#
# Requires installation of MozRepl from CPAN, Firefox, Zotero, and MozRepl
#                          firefox extension.
#
# The bibtex file will be output to stdout
#
# Jason Friedman (write.to.jason@gmail.com, www.curiousjason.com)
#
# Last updated: 4th October 2015: Changed timeout to 120 seconds (for large collections)
# Added line translatorObj.setLibraryID(null) to make work with Zotero version >= 4.0.27.1
# (thanks to Werner Koch <cobbystreet@zoho.com> )

use strict;
use warnings;

use File::Temp qw/ tempfile/;
use MozRepl;

# temporary file to store bibliography
(undef,my $filename) = tempfile();

my $repl = MozRepl->new;
# Make it quiet
$repl->setup_log([qw/error fatal/]);
$repl->setup;

#Set the timeout to 120 seconds
$repl->client->{telnet}->timeout(120);

my $executestring = "filename = '$filename';";
$executestring .= q|var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(filename);
var zotero = Components.classes['@zotero.org/Zotero;1'].getService(Components.interfaces.nsISupports).wrappedJSObject;
var translatorObj = new Zotero.Translate('export');
var collections = Zotero.getCollections();
var collection = collections[2];
translatorObj.setCollection(collection);
translatorObj.setLocation(file);
translatorObj.setTranslator('9cb70025-a888-4a29-a210-93ec52da40d4');
translatorObj.setLibraryID(null);
translatorObj.translate();|;

$repl->execute($executestring);

# print to stdout
open(FH, $filename) or die "Can't open $filename: $!";
foreach(<FH>){
print;
}
print "\n";
close(FH);
# delete the temporary file
unlink($filename);
