#!/usr/bin/env sh
export PATH=/usr/local/bin:$PATH

NC='\033[0m'

print_error() {
  RED="\033[0;31m"
  printf "${RED}ERROR: $1${NC}\n"
}

print_success() {
  GREEN="\033[0;32m"
  printf "${GREEN}SUCCESS: $1${NC}\n"
}
print_warning() {
  ORANGE="\033[0;33m"
  printf "${ORANGE}WARNING: $1${NC}\n"
}

print_hr() {
  echo "----------"
}

npm_installed() {
  whichnpm=`which npm`

  if ! [ $whichnpm ]; then
    echo "Error: Make sure nodejs and npm are installed globally"
    exit 1
  fi
}
npm_installed

run_npm_install() {
  npm install
}

print_hr
print_success "START: NPM INSTALL"
print_hr
run_npm_install
print_hr
print_success "END: NPM INSTALL"
print_hr
echo

lint_staged_files() {
  staged_js_files=()

  while read st file; do
    if [ "$st" == 'D' ]; then
      continue;
    fi

    if [[ "$file" =~ \.js$ ]] && ! [[ "$file" =~ \.min\.js$ ]]; then
      staged_js_files+=($file)
    fi
  done <<<"$(git diff --cached --name-status)"

  if [ ${#staged_js_files[@]} == 0 ]; then
    print_warning "No JavaScript files were staged :("
    print_hr
    return 0
  fi

  echo "Staged JavaScript files:"
  print_hr
  printf '%s\n' "${staged_js_files[@]}"
  print_hr

  root_dir=`git rev-parse --show-toplevel`
  eslintrc="$root_dir/.eslintrc.js"
  eslint_command="$root_dir/node_modules/.bin/eslint"

  if [ ! -f "$eslint_command" ]; then
    print_error "eslint not instaled. Install eslint as a devDependency"
    print_error "e.g. npm i -D eslint"
    return 1
  fi

  if [ -f "$eslintrc" ]; then
    eslint_command+=" -c ${eslintrc}"
  else
    print_warning "missing .eslintrc.js file. eslint config from of the parent directories or the default eslint config will be used"
  fi

  eslint_command+=" ${staged_js_files[@]}"

  if ! eval $eslint_command; then
    return 1
  fi
  return 0
}

error_code=0

print_hr
print_success "START: eslint..."
print_hr

if ! eval lint_staged_files; then
  error_code=1
fi

print_hr
print_success "END: eslint..."
print_hr


if [ $error_code != 0 ]; then
  print_warning "Changes were not committed due to errors"
  print_hr
fi
exit $error_code
