#!/bin/bash
# Script per fer les tapes dels treballs del departament
# TapesVariades
#
echo $0 $1 $2 $3 $4 >> aa
PrOgRaM="`basename "$0"`"
function Error_Avortant(){ echo -e "\nERROR a ${PrOgRaM}: ${1}.\nAvortant...\n" ;  exit 1 ; }
function Help(){ echo -e "\nÚs:\n
${PrOgRaM} -t 'TiToLtReBaLl linia 1 [\\\\\\\\ TiToLtReBaLl linia 2 ... ]' \"Autor\" Num
${PrOgRaM} --tesis 'TiToLtReBaLl linia 1 [\\\\\\\\ TiToLtReBaLl linia 2 ... ]' \"Autor\" Num
${PrOgRaM} -tr 'TiToLtReBaLl linia 1 [\\\\\\\\ TiToLtReBaLl linia 2 ... ]' \"Autor\"
${PrOgRaM} --treball-recerca 'TiToLtReBaLl linia 1 [\\\\\\\\ TiToLtReBaLl linia 2 ... ]' \"Autor\"

NOTA: Les cometes simples al voltant del títol són obligatòries!!
" ;  exit 1 ; }
#
case "$1" in
     -t | --tesis) if test $# -ne 4 ; then Help; fi ;;
     -tr | --treball-recerca) if test $# -ne 3 ; then Help; fi ;;
     -h | --help | *) Help ;;
esac
#
rm -rf /tmp/${PrOgRaM}-$USER.*/
Fitxer_Temporal=`mktemp -d /tmp/${PrOgRaM}-$USER.XXXXXX`
if [ $? -ne 0 ] || ! test -d "$Fitxer_Temporal" ; then Error_Avortant "no es pot crear el directori temporal" ; fi
#
declare -a NomMesos=(""
   "gener" "febrer" "març" "abril" "maig" "juny" "juliol" "agost"
   "setembre" "octubre" "novembre" "desembre"
)

case "$1" in
     -t | --tesis)
        TiToLpAgInA="\vspace*{71pt}\par\par\strut"
        PeUpAgInA="N\'um.\ $4 --- `date "+%Y"`" ;;
     -tr | --treball-recerca)
        TiToLpAgInA="\fontsize{45}{16pt}\selectfont
\begin{center} TREBALLS\\\\[20pt] DE RECERCA \end{center}"
        PeUpAgInA="${NomMesos[`date "+%m"`]} `date "+%Y"`" ;;
esac

TiToLtReBaLl="`echo "$2" | sed "s/[\ ]*$//"`"
if test `echo "$TiToLtReBaLl" | sed 's/\o134\o134\o134\o134/\o376/g' | tr -cd '\376' | wc -c` -ge 2 ; then TiToLtReBaLl="\fontsize{22.5}{31pt}\selectfont $TiToLtReBaLl"
else TiToLtReBaLl="\fontsize{30}{41pt}\selectfont $TiToLtReBaLl"
fi
#
cd "$Fitxer_Temporal"
cat <<EOF > "${PrOgRaM}.tex"
\documentclass[a4paper]{article}
\pagestyle{plain}
\usepackage[utf8x]{inputenc}
\usepackage{times}
\nofiles
% Mides
\topmargin=-.75truecm
\addtolength{\oddsidemargin}{1mm} %%Per imprimir a una Stylus
%
\makeatletter
\def\@oddfoot{\fontsize{12}{15pt}\selectfont\hfil{\normalsize  ${PeUpAgInA}}\hfil}
\makeatother
\begin{document}
%
${TiToLpAgInA}
\par\par\vspace*{4cm}\par\par
%
\begin{center}
${TiToLtReBaLl} \\\\[25pt]
\fontsize{18}{35pt}\selectfont $3
\end{center}
\end{document}
%
EOF
if ! test -w "${PrOgRaM}.tex" ; then Error_Avortant "no es pot crear el fitxer temporal" ; fi
#
pdflatex --interaction batchmode "${PrOgRaM}.tex" > /dev/null
if ! ( test $? -eq 0  && test -e "${PrOgRaM}.pdf" ) ; then
    Error_Avortant "el fitxer pdf no s'ha generat correctament"
fi
cd -  > /dev/null
mv "${Fitxer_Temporal}/${PrOgRaM}.pdf" "${PrOgRaM}.pdf"
if ! test -e "${PrOgRaM}.pdf" ; then Error_Avortant "el fitxer pdf no s'ha guardat correctament" ; fi
rm -rf "${Fitxer_Temporal}"
exit 0
#
