#!/usr/bin/perl

use File::Basename;
use Cwd;

$home = $ENV{HOME};

$latexmk = "latexmk";
#$latexmk .= " -r /usr/local/share/texmf/tex/latex/enstb/configs/config.latexmk" unless -e "$home/.latexmkrc";

@files = ();

$coursname = "cours";
$sujetname = "sujet";

$outtype = "pdf";
$silent = 1;
$force = 0;
$clean = 1;
$silence = "";
$correc = "nocor";
$notesens = "nonotes";
$docname = $sujetname;
$rename = "yes";
$cours = 0;
$extname = "";
@add = ();
@del = ();
$snm = 0;
$aux = 0;

foreach $target (@ARGV) {
  if ($target eq "-d") {
    $silent = 0;
  } elsif ($target eq "-f") {
    $force = 1;
  } elsif ($target eq "-dd") {
    $silent = 0;
    $clean = 0;
  } elsif ($target eq "-handout") {
    $outtype = "ps";
  } elsif ($target eq "-snm") {
    $snm = 1;
  } elsif ($target eq "-aux") {
    $aux = 1;
  } elsif ($target eq "-cor") {
    $correc = "cor";
    $sujetname = "correction";
  } elsif ($target eq "-notes") {
    $notesens = "notes";
    $sujetname = "notesenseignants";
  } elsif ($target eq "-norename") {
    $rename = 0;
  } elsif ($target eq "-mineure") {
      #    @add = ("mineure");
      @add = ("glpo");
    @del = ("majeure");
    $extname = "_mineure";
  } elsif ($target eq "-booklet") {
    @add = ("booklet");
    $extname = "_booklet";
  } elsif ($target eq "-booklet_mineure") {
    @add = ("glpo,booklet");
    @del = ("majeure");
    $extname = "_booklet_mineure";
  } elsif ($target =~ /^-cours=(.+)$/) {
    $coursname = $1;
  } elsif ($target =~ /^-sujet=(.+)$/) {
    $sujetname = $1;
    if ($correc eq "cor") {
      $sujetname = "$sujetname-correction";
    }
    if ($notesens eq "notes") {
      $sujetname = "$sujetname-notesenseignants";
    }

  } elsif ($target =~ /^-/) {
    die "Bad option [$1], only: -d, -dd, -f, -handout, -cours, -cor, -notes, -mineure, -cours=, -sujet=!\n, -booklet, -booklet_mineure";
  } else {
    @files = (@files, $target);
  }
}

if ($force) {
  $latexmk .= " -f";
}

if ($silent) {
  $silence = ">> /dev/null 2>&1";
}

foreach $target (@files) {
  $name = basename($target,(".tex"));
  $dest = dirname($target);
  if (isCours($name)) {
    $cours = 1;
    $docname = $coursname;
  } else {
    $cours = 0;
    $docname = $sujetname;
  }
  unless ($rename) {
    $docname = $name;
    if ($correc eq "cor") {
      $docname .= "-correction";
    }
    if ($notesens eq "notes") {
      $docname .= "-notesenseignants";
    }
  }

  $docname .= $extname;
  if ($outtype eq "ps") {
    if ($cours) {
      $docname .= "-4";
    } else {
      $docname .= "-2";
    }
  }

  if ($dest ne ".") {
    $previousdir = getcwd();
    chdir($dest);
  }

  print "in ".getcwd()." generating documents\n";

  @addtemp = @add;
  @deltemp = @del;
  if ($correc eq "cor") {
    @addtemp = ("correction",@addtemp);
  }
  if ($notesens eq "notes") {
    @addtemp = ("notesenseignants",@addtemp);
  }
  if ($outtype eq "ps") {
    @addtemp = ("handout",@addtemp);
  }
  substitute($name,\@addtemp,\@deltemp);
  generate("$name-tmp","$docname");
  if ($clean) {
    cleanup("$name-tmp");
    cleanup("$name");
    cleanup("uml");
    unlink("$name-tmp.tex");
    #unlink("uml.tex");
    unlink("temp.out");
    unlink("log");
    unlink(<diag*.eps>);
    unlink(<diag*.pdf>);
    unlink(<herediag*.*>);
    unlink(<herediag*.*>);
    unlink(<*~>);
    unlink(<*.texbak>);
  }
  
  if ($dest ne ".") {
    chdir($previousdir);
  }

}

sub generate {
  my $name = shift;
  my $destname = shift;

  system("$latexmk -pdf $name $silence") == 0 or die "Cannot generate [$name.pdf]!\n";
  rename("$name.pdf","$destname.pdf");
  print("\t$destname.pdf generated\n");
  rename("$name.snm","$destname.snm")if $snm;
  rename("$name.aux","$destname.aux")if $aux;
}

sub substitute {
  my $name = shift;
  my $versionstoadd = shift;
  my $versionstodel = shift;
  my $destname = "$name-tmp";
  my $options = "";
  my $package = "";
  local(*IN);
  local(*OUT);

  $name .= ".tex";
  $destname .= ".tex";

  open(IN,$name) or die "Could not open input file [$name]!\n";
  open(OUT, ">$destname") or die "Could not create [$destname]!\n";
  while(<IN>) {
    if (/^[^%\\]*\\documentclass(\[([0-9a-zA-Z,=]*)\])?{(\w+)}/) {
      if ($2) {
	$options = $2;
      } else {
	$options = "";
      }
      $package = $3 if ($3);
      foreach $option (@$versionstoadd) {
	$options = "$option,$options" unless ($options =~ /$option/);
      }
      foreach $option (@$versionstodel) {
	$options =~ s/$option//g;
      }
      $options =~ s/,+/,/g;
      $options =~ s/^,//g;
      $options =~ s/,$//g;
      if ($options eq "") {
	print OUT "\\documentclass{$package}\n";
      } else {
	print OUT "\\documentclass[$options]{$package}\n";
      }
    } elsif (/^[^%\\]*\\matiere\{Alcatel\}.*/) {
      print OUT;
      open(DESC,"desc.txt") or die "Could not open input file [desc.txt]!\n";
      while (<DESC>) {
	if (/^Titre : (.+)/) { print OUT "\\title{$1}\n"; }
	if (/^Acronyme : (.+)/) { print OUT "\\numero{Module $1}\n\n"; }
      }
      close(DESC);
    } else {
      print OUT;
    }
  }
  close(IN);
  close(OUT);
}

sub cleanup {
  local $name = shift;

  @ext = ("aux", "aux.bak", "bbl", "blg", "ind", "idx", "idx.bak", 
	  "ilg", "loe", "lof", "log", "lot", "nav", "out", "snm", "thm", "toc", 
	  "toc.bak", "dvi", "vrb","ps", "fdb_latexmk", "fls");

  foreach $ext (@ext) {
    unlink("$name.$ext");
  }
  unlink("texput.log");
  unlink("x.log");
}

sub isCours {
  my $name = shift;
  my $res = 0;
  local(*IN);

  $name .= ".tex";

  open(IN,$name) or die "Could not open input file [$name]!\n";
  while(<IN>) {
    if (/^[^%\\]*\\documentclass(\[([0-9a-zA-Z,]*)\])?{(\w+)}/) {
      if ($2) {
	$res = ($2 =~ /cours/);
      }
    }
  }
  close(IN);
  return $res;
}
