#!/bin/sh
# Run code linters on Apport.
#
# Test against the source tree when run in the source tree root.

# Copyright (C) 2007 - 2012 Canonical Ltd.
# Author: Martin Pitt <martin.pitt@ubuntu.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.  See http://www.gnu.org/copyleft/gpl.html for
# the full text of the license.

set -eu

PYTHON_FILES="apport apport_python_hook.py data problem_report.py setup.py tests"
PYTHON_SCRIPTS=$(find bin data gtk kde -type f -executable ! -name apport-bug ! -name apport-collect ! -name is-enabled ! -name root_info_wrapper)

if type black >/dev/null 2>&1; then
    echo "Running black..."
    black -C --check --diff ${PYTHON_FILES} ${PYTHON_SCRIPTS}
else
    echo "Skipping black tests, black is not installed"
fi

if type isort >/dev/null 2>&1; then
    echo "Running isort..."
    isort --check-only --diff ${PYTHON_FILES} ${PYTHON_SCRIPTS}
else
    echo "Skipping isort tests, isort is not installed"
fi

if type pycodestyle >/dev/null 2>&1; then
    echo "Running pycodestyle..."
    # . catches all *.py modules; we explicitly need to specify the programs
    pycodestyle --max-line-length=79 -r --ignore=E203,W503 ${PYTHON_FILES} ${PYTHON_SCRIPTS}
else
    echo "Skipping pycodestyle tests, pycodestyle is not installed"
fi

if type pydocstyle >/dev/null 2>&1; then
    pydocstyle_version=$(pydocstyle --version)
    pydocstyle_major_version=$(echo "$pydocstyle_version" | cut -d. -f1)
    if test "$pydocstyle_major_version" -ge 6; then
        echo "Running pydocstyle..."
        pydocstyle ${PYTHON_FILES} ${PYTHON_SCRIPTS}
    else
        echo "Skipping pydocstyle tests, pydocstyle $pydocstyle_version is too old"
    fi
else
    echo "Skipping pydocstyle tests, pydocstyle is not installed"
fi

# pyflakes3, if available
if type pyflakes3 >/dev/null 2>&1; then
    echo "Running pyflakes3..."
    pyflakes3 ${PYTHON_FILES} ${PYTHON_SCRIPTS}
else
    echo "Skipping pyflakes3 tests, pyflakes3 is not installed"
fi

if type pylint >/dev/null 2>&1; then
    echo "Running pylint..."
    pylint ${PYTHON_FILES} ${PYTHON_SCRIPTS}
else
    echo "Skipping pylint tests, pylint is not installed"
fi

# assert that there are no hardcoded "Ubuntu" names
out=$(grep -rw Ubuntu apport/*.py gtk/apport-gtk* kde/* bin/* | grep -v Debian | grep -v X-Ubuntu-Gettext-Domain | grep -v '#.*Ubuntu') || :
if [ -n "$out" ]; then
    echo "Found hardcoded 'Ubuntu' names, use DistroRelease: field or lsb_release instead:\n\n$out" >&2
    exit 1
fi
