#!/bin/bash


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

# 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: meta.yaml | 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: meta.yaml | awk -F': ' '{print $2}'`
if [ -z "$template" ]; then
  template=light
fi

# read the formats from the md's yaml
if [ ! -z "$1" ]; then
  formats="$1"
else
  formats=`grep formats: meta.yaml | awk -F': ' '{print $2}'`
fi


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}"
  
  flags="--toc --number-sections"
  if [[ "${format}" == "pdf" ]] || [[ "${format}" == "tex" ]]; then
    template_file="${template}.tex"
    flags="${flags} --listings --pdf-engine=xelatex"
    if [[ "${format}" == "tex" ]]; then
      flags="${flags} --biblatex"
    fi
  elif [[ "${format}" == "html" ]]; then
    template_file="${template}.html"
    flags="${flags} --katex"
  elif [[ "${format}" == "docx" ]]; then
    flags="${flags} --reference-doc=CS-Book.docx"
  else
    template_file="${template}.${format}"
  fi

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

  if [ -z "`git check-ignore ${name}.${format}`" ]; then
    echo ${name}.${format} >> .gitignore
  fi
  
  # post-process
  if [[ "${format}" == "html" ]]; then
    sed -i 's/<table>/<table class="table table-responsive table-striped">/' ${name}.${format}
    sed -i 's/<blockquote>/<blockquote class="blockquote">/' ${name}.${format}
  fi
done
