#!/bin/bash


for i in m4 pandoc xelatex locale grep wc; do
 if [ -z "`which $i`" ]; then
   echo "error: $i is not installed"
   exit 1
 fi
done

# TODO: arg $1 da el formato, i.e. ./make.sh docx

# the document name is the current directory name
name=`basename $PWD`
if [ ! -e ${name}.md ]; then
  echo "error: ${name}.md does not exist"
  exit 1
fi

# get the date right
language=`grep lang ${name}.md | awk -F: '{print $2}' | sed s/-/_/`
LC=`locale -a | grep $language | head -n1`
if [ -z "$LC" ]; then
  echo "error: locale for language $language is not installed, run"
  echo "dpkg-reconfigure locales"
  echo "or equivalent (or change the document's language)"
  exit 1
fi

# see how we are supposed to write the date, but
# replace %m with %b to get a string for the month
dateformat=`LC_ALL=${LC} locale d_fmt | sed s/m/b/`
currentdate=`LC_ALL=${LC} date +${dateformat}`
currentdateedtf=`LC_ALL=${LC} date +%Y-%m-%d`

# read the template name from the md's yaml, otherwise default to light
template=`grep template ${name}.md | awk -F': ' '{print $2}'`
if [ -z "$template" ]; then
  template=light
fi

# read the formats from the md's yaml
formats=`grep formats ${name}.md | awk -F': ' '{print $2}'`


branch=`git rev-parse --abbrev-ref HEAD`
dochash=`git rev-parse --short HEAD`

if [ -e "baserev" ]; then
  basehash=`cat baserev`
else
  basehash=`git rev-parse HEAD`
fi

headepoch=`git log -1 --format="%ct"`
headdate=`LC_ALL=${DATELC} date -d@${headepoch} +${dateformat}`
headdateedtf=`LC_ALL=${DATELC} date -d@${headepoch} +%Y-%m-%d`

tag=`git tag --sort=-version:refname | head -n1`

if [ -z "${tag}" ]; then
  revision="DRAFT"
  docver=`git rev-list ${basehash}..HEAD | wc -l`
else
  revision=${tag}
  docver=`git rev-list ${tag}..HEAD | wc -l`
fi

if [ ${docver} -ne 0 ]; then
  revision="${revision}${docver}"
fi

hash=`git rev-parse --short HEAD`

# hook-pre
if [ -e hook-pre.sh ]; then
 ./hook-pre.sh
 if [ $? != 0 ]; then
   echo "hook-pre.sh failed!"
   exit 1
 fi
fi


# if the current working tree is not clean, we add a "+"
# (should be $\epsilon$, but it would screw the file name),
# set the date to today and change the author to the current user,
# as it is the most probable scenario
if [ -z "`git status --porcelain`" ]; then
  date=${headdate}
  dateedtf=${headdateedtf}
else
  dochash="${hash}+$\epsilon$"
  revision="${revision}+"
  date=${currentdate}
  dateedtf=${currentdateedtf}
fi




cat << EOF > hash.yaml
---
hash: ${dochash}
rev: ${revision}
date: ${date}
...
EOF

for format in ${formats}; do

  echo "md -> ${format}"
  
  vector_format="pdf"
  flags="--number-sections"
  if [[ "${format}" == "pdf" ]] || [[ "${format}" == "tex" ]]; then
    template_file="${template}.tex"
    flags="${flags} --listings --pdf-engine=xelatex"
  elif [[ "${format}" == "html" ]]; then
    template_file="${template}.html"
    flags="${flags} --mathjax"
    vector_format="svg"
  else
    template_file="${template}.${format}"
  fi

  if [ -e "${template_file}" ]; then
    template_spec="--template $template_file"
  fi
  
  m4 -Dvector_format=${vector_format} header.m4 ${name}.md hash.yaml |\
    pandoc -s ${flags} ${template_spec} --filter pandoc-crossref -o ${name}.${format} || exit 1

  if [ -z "`git check-ignore ${name}.${format}`" ]; then
    echo ${name}.${format} >> .gitignore
  fi
done
