#!/usr/bin/env bash

HOOKS_VENV=$(pwd)/hooksvenv

# Find all staged Python files, and exit early if there aren't any.
PYTHON_FILES=()
while IFS=$'\n' read -r line; do PYTHON_FILES+=("$line"); done \
  < <(git diff --name-only --cached --diff-filter=AM | grep --color=never '.py$')
if [ ${#PYTHON_FILES[@]} -eq 0 ]; then
  echo 'No python files to format. Skip formatting'
  exit 0
fi

# Check for unstaged changes to files in the index.
CHANGED_FILES=()
while IFS=$'\n' read -r line; do CHANGED_FILES+=("$line"); done \
  < <(git diff --name-only "${PYTHON_FILES[@]}")
if [ ${#CHANGED_FILES[@]} -gt 0 ]; then
  echo 'You have unstaged changes to some files in your commit; skipping '
  echo 'auto-format. Please stage, stash, or revert these changes. You may '
  echo 'find `git stash -k` helpful here.'
  echo 'Files with unstaged changes:' "${CHANGED_FILES[@]}"
  exit 1
fi

# Format all files, then exit with an error code if any have uncommitted
# changes.
echo 'Formatting all Python files . . .'

UPDATED_DIRS=$(echo "${PYTHON_FILES[@]}" | tr ' ' '\n' | xargs -I {} dirname ./{} | sort -u )

DEPLOYABLES_DIRS=$(find . -name 'setup.py' -type f ! -path '*/*env/*' -exec dirname "{}" \; 2>&1 | grep -v "Permission denied")
echo "deployables"
echo "${DEPLOYABLES_DIRS[@]}"
CHECK_DIRS=()
for i in ${DEPLOYABLES_DIRS[@]}; do
  for j in ${UPDATED_DIRS[@]}; do
    if [[ "$j" == "$i"* ]]; then
      CHECK_DIRS+=("$i")
    fi
  done
done
echo "to check"
echo "${CHECK_DIRS[@]}"

echo ${CHECK_DIRS[@]}  | tr ' ' '\n' | \
  xargs -I {} bash -c "cd {} && ${HOOKS_VENV}/bin/isort -rc . && ${HOOKS_VENV}/bin/yapf . --recursive --verbose --in-place --parallel"

CHANGED_FILES=()
while IFS=$'\n' read -r line; do CHANGED_FILES+=("$line"); done \
  < <(git diff --name-only "${PYTHON_FILES[@]}")
if [ ${#CHANGED_FILES[@]} -gt 0 ]; then
  echo 'Reformatted staged files. Please review and stage the changes.'
  echo 'Files updated: ' "${CHANGED_FILES[@]}"
  exit 1
else
  exit 0
fi
