#! /usr/local/bin/perl -w

# Given a .bib file (or several), generate an eponymous .tex file in the
# current directory that just puts all the entries in the bibliography into an
# enumerate environment.

# Copyright (C) 2007 Benoit Hudson
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 

use strict;
use File::Temp qw(tempfile tempdir);
use File::Basename qw(fileparse);

# TODO: make this a command-line thing, to choose the bibstyle.
my $bibstyle = "dsgplain";
# you probably want to:
# wget http://www.lri.fr/~filliatr/bibtex2html/examples/Joel-Brynielsson/dsgplain.bst

die "args: $0 [bibfile]\n" unless @ARGV > 0;
foreach my $file (@ARGV) {
  my ($name, $path, $suffix) = fileparse($file, qr/\.[^.]*/);

  # we'll be working in a temp subdirectory which we'll clean up.
  # the relpath hackage is to make latex understand that (note that it
  # assumes a Unix-like FS; probably easy to fix, I'm just asking whether
  # $path is absolute or relative).
  my $dir = tempdir(DIR => '.', CLEANUP => 1);
  my ($out, $outname) = tempfile(DIR => $dir, SUFFIX => '.tex');
  my ($tmpbasename) = fileparse($outname, qr/\.[^.]*/);
  my $relpath;
  if ($path =~ /^\//) {
    $relpath = $path;
  } else {
    $relpath = "../$path";
  }

  # make a file that just does a nocite on everything in the bib file.
  print $out
    ("\\documentclass{article}\n"
    , "\\begin{document}\n"
    , "\\nocite{*}\n"
    , "\\bibliographystyle{$bibstyle}\n"
    , "\\bibliography{$relpath$name}\n"
    , "\\end{document}\n");

  # compile it, creating a .bbl file that's almost exactly what we want.
  if ($bibstyle && -f "$bibstyle.bst") {
    system("cp $bibstyle.bst $dir") == 0 or die "error copying $bibstyle.bst";
  }
  system("cd $dir && latex $tmpbasename") == 0 or die "error in latex $tmpbasename\n";
  system("cd $dir && bibtex $tmpbasename") == 0 or die "error in bibtex $tmpbasename\n";

  # but not quite exactly, so go ahead and munge it while simultaneously
  # copying it out of the tempdir which is going to be cleaned.
  open(BBL, "$dir/$tmpbasename.bbl") or die;
  open(OUT, ">$name.tex") or die;
  while(<BBL>) {
    s/thebibliography.*/enumerate}/;
    s/\\bibitem.*/\\item/;
    print OUT;
  }
}
