#!/bin/bash

make

if [ "$ERL_TOP" = "" ];
then
    if [ -d "/usr/local/lib/erlang" ];
    then
        export ERL_TOP="/usr/local/lib/erlang"
    else
        export ERL_TOP="/usr/lib/erlang"
    fi
    echo Erlang installation directory is $ERL_TOP.
else
    echo Using Erlang installation in $ERL_TOP.
fi


PLT="./.refactorerl.plt"

# (re)build the dialyzer plt
if [ -a $PLT ];
then
    echo Updating Dialyzer PLT in $PLT. This should not take long...
    dialyzer --plt $PLT --check_plt
else
    echo "Initialising Dialyzer PLT in $PLT. This will take several minutes..."
    dialyzer --build_plt --output_plt $PLT --apps stdlib kernel erts mnesia syntax_tools runtime_tools eunit tools crypto compiler
fi

if [ "$1" != "-build" ]
then
    echo "Adding the files of RefactorErl to Dialyzer. This will take several more minutes..."
    dialyzer --add_to_plt --plt $PLT -r lib/referl_{core,lib,gen,slicer,ui,user,cluster}/ebin/*beam
    echo Checking for errors with Dialyzer...
    echo
    if [ $# -eq 1 ];
    then
	for i in `find -name "*$1*beam"`;
	do
            echo [${i##`pwd`}]
            dialyzer --plt $PLT -c $i -o .dialyzer_result -Wno_return >/dev/null;
            if [ $? -ne 0 ]; then
		cat .dialyzer_result | tail -n+2
		echo
            fi
	done
    else
	for i in `ls -t lib/referl_{core,lib,gen,slicer,ui,user,cluster}/ebin/*beam`;
	do
            echo [${i##`pwd`}]
            dialyzer --plt $PLT -c $i -o .dialyzer_result -Wno_return >/dev/null;
            if [ $? -ne 0 ]; then
		cat .dialyzer_result | tail -n+2
		echo
            fi
	done

    fi
    rm -f .dialyzer_result
fi
