#!/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]\
 [files [files ...]]

Python code formatter

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 isorts Python imports formatter
  --skip-black           skip black Python code formatter
USAGE
  exit 0
}


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

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

while (( "$#" )); do
  case "$1" in
    -h|--help)
      usage
      ;;
    -l|--line-length)
      LINE_LENGTH=$2
      shift 2
      ;;
    -l=*|--line-length=*)
      LINE_LENGTH="${1#*=}"
      shift
      ;;
    --skip-isort)
      SKIP_ISORT="true"
      shift
      ;;
    --skip-black)
      SKIP_BLACK="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 formatting ~ ~ ~ ~ ~
if [[ -z "${SKIP_ISORT}" ]]; then
  LINE_LENGTH="${LINE_LENGTH}" catalyst-codestyle-isort --apply -- ${FILES}
fi

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