#!/bin/bash
#
# Precommit hook which runs 'tslint' to lint TypeScript code.
#
# It gets only triggered when a file below $vtctld_web_src was changed.
vtctld_web="web/vtctld2"

git diff --cached --name-only --diff-filter=ACM | grep -q "^${vtctld_web}/src"
if [ $? -ne 0 ]; then
  # No potential TypeScript file changed. Return early.
  exit 0
fi

if [ -z "$(which tslint)" ]; then
  echo "tslint not found, please run: npm install -g tslint typescript"
  exit 1
fi

cd $vtctld_web
if [[ $? != 0 ]]; then
  echo "Failed to change to the vtctld web directory ($vtctld_web)"
  exit 1
fi

# Check for lint errors.
# Suppress npm logs to avoid that it creates a npm-debug.log file in $CWD.
errors=$(npm --loglevel=silent run lint 2>&1)
if [ $? -eq 0 ]; then
  # No lint errors. Return early.
  exit 0
fi

# Ask the user how to proceed.

# git doesn't give us access to user input, so let's steal it.
exec < /dev/tty
if [[ $? -eq 0 ]]; then
  # interactive shell. Prompt the user.
  echo
  echo "tslint suggestions were found. They're not enforced, but we're pausing"
  echo "to let you know before they get clobbered in the scrollback buffer."
  echo
  read -r -p 'Press enter to cancel, "s" to show all warnings or type "ack" to continue: '
  if [ "$REPLY" = "ack" ]; then
    exit 0
  fi
  if [ "$REPLY" = "s" ]; then
    echo
    echo "$errors"
  fi
else
  # non-interactive shell (e.g. called from Eclipse). Just display the errors.
  echo "$errors"
fi

exit 1
