#!/bin/csh
#
# packngotex.sh    Script to pack up a (la)tex doc and graphics.
#
# Packs: graphics, latex sources and, if found, final pdf
#
# This uses -recorder tex option to do most of the work by generating the list
# of files opened in <jobname.fls>
#
# This is better than a previous script that trawled through the aux file,
# as the .fls file has full paths to everything, even things in my TEXINPUTS
# path (which only have relative paths in the aux file). Also, it should work
# (untested) on files with multiple inputs/includes, because the .fls
# is a full list of anything that was input to latex. It also copies the source
# latex files, aux, bbl, etc., and maybe a couple of extras, but rejects anything
# that comes from the tex base installation texmf hierarchy.
#
# Steve Schwartz (s.schwartz@imperial.ac.uk)
#
# Copyright: I wrote it, but it's not rocket science so you can have it.
# I'd be happy to hear of improvements - I can see many that could be made,
# and that would be easy, but time presses on.
#
# history
#
#  SJS 2 Dec 2008  first attempt

if ($#argv < 2) then
   echo "Usage: packngotex.sh <file_stem> <target directory> [<tex-cmd>]"
   echo "<tex-cmd> defaults to pdflatex"
   exit
endif

if ($#argv == 3) then
   set texcmd=$3
else 
   set texcmd=pdflatex
endif

if (-d $2) then
   echo $2 "already exists - exiting"
   exit
endif

mkdir $2

if (-e /tmp/packngotex_cp.sh) then
   rm /tmp/packngotex_cp.sh
endif

if (-e /tmp/texstem) then
   rm /tmp/texstem
endif

# put temporary files in /tmp to be sure user can execute
# (in my system, I keep .tex files on a fat32 partition, which
# is not executable)

# run texcmd to generate jobname.fls file with list of files
# The .fls file will end up alongside the other output files (aux, etc.)

$texcmd -recorder  $1.tex

# Look for the texmf.cnf file, which lives (at least in texlive) in the top install
# directory.

kpsewhich texmf.cnf > /tmp/texstem
set texstem=`sed  -e 's|/texmf.cnf||' /tmp/texstem`

# Now throw away all lines that correspond to files from the tex installation
# and only then keep the INPUT lines.
grep -v $texstem $1.fls | grep INPUT > /tmp/packngotex_cp.sh

# Put the cp commands in the script, make executable, and run
# Note the .fls has multiple copies of each file entry, so use -u
# option to avoid multiple copying
sed -i -e 's/INPUT/cp -u/;s/$/ $1/' /tmp/packngotex_cp.sh
chmod u+x /tmp/packngotex_cp.sh
/bin/csh /tmp/packngotex_cp.sh $2

# manually copy the final pdf and/or dvi
if (-e $1.pdf) then
   cp $1.pdf $2
endif

if (-e $1.dvi) then
   cp $1.dvi $2
endif

#bundle
tar -cvzf $1.tgz $2

# cleanup
rm /tmp/texstem
rm /tmp/packngotex_cp.sh

exit