#!/bin/bash
# Bash script to background while working on a .tex-file
# Copyright (C) 2006  Anders Breindahl
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


FILE="$1"
if [ $# -lt 1 ] || [ $# -gt 1 ]; then
  i=1
  for file in *.tex; do
    if [ $i -gt 2 ]; then
      break
    fi
    i=$((i+1))
  done
  if [ $i -gt 2 ]; then
    echo "Wrong amount of arguments to $0. :S"
    echo "Please specify the .tex to work on, as an argument."
    exit
  else
    echo "Wrong amount of arguments to $0. :S"
    if ! [ "$file" == '*.tex' ]; then
      FILE="$file"
      echo "No worry, though. Using $FILE."
    fi
  fi
fi
md5sum="0"

while [ 1 ]; do
  if [ -f "$FILE" ] && [ "$md5sum" != "$(md5sum "$FILE")" ]; then
    echo -en   "\rFile renewed, compiling...       " # ugly, I know.
    output="$(latex -halt-on-error "$FILE")"
    md5sum="$(md5sum "$FILE")"
    if [ -z "$(echo "$output" | grep "No pages of output")" ]; then
      echo -en "\rCompilation succeeded @ $(date +%H:%M:%S)."
      if [ -n "$(echo "$output" | grep "Overfull")" ] ||
         [ -n "$(echo "$output" | grep "Underfull")" ]; then
        echo -en "\n"
        echo -n "$output" | grep "Overfull"
        echo -n "$output" | grep "Underfull"
      fi
      killall -USR1 xdvi.bin
      echo -ne "\n"
    else
      echo -ne "\n"
      echo -e "\rCompilation failed @ $(date +%H:%M:%S). Failure follows:"
      echo "$output" | grep --after-context 3 "^!" | grep -v "No pages of output"
    fi
  fi
  echo -en "\rReady, $(date +%H:%M:%S)..."
  sleep 1
done

