#!/bin/bash
# fichier ROIA2021-RefPerSys/produce-pdf.sh
# file ROIA2021-RefPerSys/produce-pdf.sh
## the script to make the PDF file using pdflatex
declare -a rps_pdflatex_args

rpsafia_base=Starynkevitch-RefPerSys

if [ "$1" = "-d" -o "$1" = "--debug" ]; then
    rps_pdflatex_args=(-debug-format -halt-on-error -file-line-error  -interaction=batchmode  -recorder -shell-escape)
    shift
else
    rps_pdflatex_args=(-halt-on-error -file-line-error -interaction=batchmode -recorder -shell-escape)
fi

function rps_run_pdflatex () {
    if pdflatex $rps_pdflatex_args $* ; then
	printf "pdflatex good for %s\n" "$@"
    else
	printf "pdflatex failed for %s\n" "$@"
    fi
}


### inkscape could be in /usr/local/bin since inkscape 1.0 is needed
inkscape --version
pdflatex --version

## backup the old pdf file
if [ -f $rpsafia_base.pdf ]; then
    /bin/mv -vfb $rpsafia_base.pdf $rpsafia_base.pdf~
fi



# generate the git tag of paper and date
rpsrawgittag="$(git log --format=oneline -1 --abbrev=16 --abbrev-commit -q|cut -d' ' -f1)"
export RPSAFIA_GIT_TAG=$rpsrawgittag

if git status -s | grep -q '^.M' > /dev/null ; then
    [ -f generated/git-commit.tex ] && mv -vf generated/git-commit.tex generated/git-commit.tex+dirty%
    rpsafiagittag=$(printf "%s++" "$bmrawgittag")
else
    [ -f generated/git-commit.tex ] && mv -vf generated/git-commit.tex generated/git-commit.tex+clean~
    rpsafiagittag=$(printf "%s..." "$bmrawgittag")
fi
printf "\\\\newcommand{\\\\rpsafiagitcommit}[0]{%s}\n" "$rpsafiagittag" > generated/git-commit.tex
/usr/bin/git log -1 '--format=tformat:\newcommand{\rpsafiagitdate}[0]{%ad}' --date=format:%Y-%b-%d >> generated/git-commit.tex

# generate the dates
/bin/date +'\newcommand{\rpsafiadoctimestamp}[0]{%c}%n\newcommand{\rpsafiadocdate}[0]{%b %d, %Y}' >generated/timestamp.tex



ln -svf $HOME/RefPerSys/doc/bib-refpersys.bib bib-refpersys.bib

rps_run_pdflatex --draftmode $rpsafia_base && /bin/true
bibtex $rpsafia_base < /dev/null
rps_run_pdflatex $rpsafia_base && /bin/true
texindy -v -C utf8 -I latex $rpsafia_base.idx
rps_run_pdflatex $rpsafia_base
