#!/usr/bin/env bash

# Cause the script to exit if a single command fails
set -e  # o pipefail -v

usage()
{
  cat << USAGE >&2
usage: $(basename "$0") [-h] [-l LINE_LENGTH] [--skip-isort] [--skip-black]\
 [--skip-flake8] [files [files ...]]

Python code style checker

positional arguments:
files                    files that need to be checked, all files\
 with \`.py\` extension will be checked if no files are specified

optional arguments:
  -h, --help             show this help message and exit
  -l, --line-length INT  maximum length that any line may be
  --skip-isort           skip isort Python imports checker
  --skip-black           skip black Python code checker
  --skip-flake8          skip flake8 linter
USAGE
  exit 0
}


# ~ ~ ~ ~ ~ environment variables ~ ~ ~ ~ ~

FILES=""
LINE_LENGTH=79
SKIP_ISORT=""
SKIP_BLACK=""
SKIP_FLAKE8=""

while (( "$#" )); do
  case "$1" in
    -h|--help)
      usage
      ;;
    -l|--line-length)
      LINE_LENGTH=$2
      shift 2
      ;;
    --skip-isort)
      SKIP_ISORT="true"
      shift
      ;;
    --skip-black)
      SKIP_BLACK="true"
      shift
      ;;
    --skip-flake8)
      SKIP_FLAKE8="true"
      shift
      ;;
    -*|--*=) # unsupported flags
      echo "Error: Unsupported flag $1" >&2
      exit 1
      ;;
    *) # preserve positional arguments
      FILES="${FILES} $1"
      shift
      ;;
  esac
done

# check all python files if `FILES` unspecified
if [[ -z "${FILES}" ]]; then
  # check whole git repo if possible
  if git rev-parse --git-dir > /dev/null 2>&1; then
    ROOT="$(git rev-parse --show-toplevel)"
    builtin cd "${ROOT}" || exit 1
  fi

  FILES=.
fi


# ~ ~ ~ ~ ~ code checking ~ ~ ~ ~ ~
if [[ -z "${SKIP_ISORT}" ]]; then
  LINE_LENGTH="${LINE_LENGTH}" catalyst-codestyle-isort \
    --diff \
    --check-only \
    -- ${FILES}
fi

if [[ -z "${SKIP_BLACK}" ]]; then
  black --check --diff --line-length "${LINE_LENGTH}" -- ${FILES}
fi

if [[ -z "${SKIP_FLAKE8}" ]]; then
  LINE_LENGTH="${LINE_LENGTH}" catalyst-codestyle-flake8 \
    --show-source \
    --statistics \
    --count \
    -- ${FILES}
fi