#! /usr/bin/env bash

#
# Prelude - make bash behave sanely
# http://redsymbol.net/articles/unofficial-bash-strict-mode/
#
set -euo pipefail

# Make pushd & popd silent
pushd () {
  command pushd "$@" > /dev/null
}

popd () {
  command popd "$@" > /dev/null
}

export EXIT_CODE=0


function lint_changed() {
  # Allow lint to be ran from outside of the root directory
  local git_root
  git_root=$(git rev-parse --show-cdup)
  git_root=${git_root:-./}

  local subdirs
  subdirs=$(find "$git_root" -maxdepth 2 -mindepth 2 -name 'Makefile' -printf '%h\n')


  for directory in $subdirs
  do
    pushd "$directory"

    local npm_bin="node_modules/.bin"
    local eslint="$npm_bin/eslint"

    function lint() {
      local to_lint
      to_lint=$(git diff --staged --diff-filter=ACMTUXB --name-only -- '*.j'{s,sx})
      echo $to_lint
      echo $eslint

      if [ "$to_lint" ]; then
        $eslint "$to_lint" -c ".eslintrc" || EXIT_CODE=$?
      fi
    }

    lint
    popd
  done
}

lint_changed
if [[ "$EXIT_CODE" -gt "0" ]]; then
  exit $EXIT_CODE
fi
make test

echo "⚡️  changed files pass eslint! ⚡️"
