#!/bin/bash

function run_pep8 {
    pep8 ${@}
}

function run_pyflakes {
    pyflakes ${@}
}

function changed_files {
    git diff --cached --name-only --diff-filter=ACM
}

function write_staged {
    while read file; do
        name=`basename $file`
        tmpfile=`mktemp /tmp/XXXXX-${name}`
        git show ":$file" > $tmpfile
        echo "$tmpfile"
    done
}

case "${1}" in
    --about )
        echo "Perform static analysis of python source files"
        ;;
    * )
        # call out to tools
        files=`changed_files | grep -e '\.py$' | write_staged`
        if [ -z "$files" ]; then
            exit 0
        fi

        if ! which pep8 pyflakes > /dev/null; then
            echo "Please install pep8 and pyflakes: pip install pep8 pyflakes"
            exit 0
        fi

        run_pep8 $files
        pep8_status=$?
        run_pyflakes $files
        pyflakes_status=$?
        rm $files
        test "$pep8_status" -eq 0 -a "$pyflakes_status" -eq 0
        exit $?
        ;;
esac
