#!/usr/bin/env bash

RESULT=tmpfile
ROOT=..
ERRORSTATUS=0

# lookfor ( $1=what, $2=reason, $3=source module exception )
lookfor () {
    rm -f "$RESULT"
    darcs query manifest --repodir="$ROOT" | grep '\.l\?hs$' | while read f; do
        grep -Hnwe "$1" "$ROOT/$f" | grep -v "$3\.$1" | \
        grep -v ":[0-9]\+:import " | grep -Fv "ratify $1: " >> "$RESULT"
    done
    if [ -s "$RESULT" ]; then
        echo "Found the following unratified uses of $1:"
        # ugly sed expresion to fix relative paths; think pretty cat
        sed -e 's/[^:]*\/\.\///' "$RESULT"
        echo "$2"
        echo "Comment 'ratify $1: <why>' on the same line to allow it"
        echo
        ERRORSTATUS=1
    fi
    rm -f "$RESULT"
}


lookfor readFile \
        "readFile doesn't ensure the file is closed before it is deleted!" \
        B # importing readFile from Data.ByteString as B, is allowed

lookfor hGetContents \
        "hGetContents doesn't ensure the file is closed before it is deleted!"

# look for tabs in haskell source
rm -f "$RESULT"
darcs query manifest --repodir="$ROOT" | grep '\.l\?hs$' | while read f; do
    grep -FHnwe "	" "$ROOT/$f" >> "$RESULT"
done
if [ -s "$RESULT" ]; then
    echo "Found the following lines with unwanted tabs:"
    # ugly sed expresion to fix relative paths; think pretty cat
    sed -e 's/[^:]*\/\.\///' "$RESULT"
    echo
    ERRORSTATUS=1
fi
rm -f "$RESULT"

exit "$ERRORSTATUS"
