#!/bin/bash

# old versions of flake8 (trusty) cannot be called as python3 -m flake8
# newer versions can.  Its preferable to run as python -m because
# that allows us to run explicitly python or python3.
mode=""
case "$1" in
    any|cmd) mode="$1"; shift;;
esac

if [ "$mode" = "cmd" ] ||
    { [ "$mode" = "any" ] && command -v flake8 >/dev/null; }; then
    cmd=( flake8 )
else
    case "$1" in
        python|python2|python3) python="$1"; shift;;
        *) python=python3;;
    esac
    cmd=( "$python" -m "flake8" )
fi

if [ $# -eq 0 ]; then
   exes=( )
   # these dirs have python files that do not end in .py
   for f in tools/* bin/*; do
      [ -f "$f" -a "${f%.py}" = "$f" ] || continue
      read line <"$f" && [ "${line#*python}" != "$line" ] &&
         exes[${#exes[@]}]="$f"
   done
   files=( "${exes[@]}" setup.py simplestreams/ tools/ tests/ )
else
   files=( "$@" );
fi

cmd=( "${cmd[@]}" "${files[@]}" )

echo -e "\nRunning flake8:"
echo "${cmd[@]}"
"${cmd[@]}"
