#!/bin/sh

STDLIB=~/languages/agda/libs/agda-stdlib/src/
DIRECTORY=$( dirname  "$1" )
TARGETNAME=$( basename "$1" .lagda )
TARGET="$DIRECTORY"/"$TARGETNAME"

# Compute the checksum of the target
CHECK=`md5sum "$TARGET".lagda | awk '{ print $1 }'`
# If the hash file does not exist, create a dummy one
if [ ! -f "$TARGET".hash ]; then
  echo 0 > "$TARGET".hash
fi
# If the tex file hasn't been generated yet or if the
# file has changed, then (re)generate it.
if [ ! -f latex/"$TARGET".tex ] || [ $CHECK != `cat "$TARGET".hash` ]; then
  echo REGENERATE: "$TARGET".tex
  agda -i . -i "$STDLIB" --latex "$TARGET".lagda > "$TARGET".log
else
  echo FROM CACHE: "$TARGET".tex
fi
echo "$CHECK" > "$TARGET".hash
# Go back to the root directory and copy the generated tex
mkdir -p __build/"$DIRECTORY"
cp latex/"$TARGET".tex __build/"$DIRECTORY"/
