#!/usr/bin/env bash

RESULT=tmpfile
ROOT=..
ERRORSTATUS=0

# lookfor ( $1=what, $2=reason )
lookfor () {
    rm -f "$RESULT"
    darcs query manifest --repodir="$ROOT" | grep '\.l\?hs$' | while read f; do
        grep -FHnwe "$1" "$ROOT/$f" | \
        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!"

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"
