#!/usr/bin/env bash
#
# Check changed js files using jshint and jscs
#
# This script is being developed at https://github.yandex-team.ru/lego/islands-codestyle

PATCH_FILE="working-tree.patch"
NPM_BIN="./node_modules/.bin"

function cleanup {
    exit_code=$?
    if [ -f "$PATCH_FILE" ]; then
        git apply "$PATCH_FILE" 2> /dev/null
        rm "$PATCH_FILE"
    fi
    exit $exit_code
}

trap cleanup EXIT SIGINT SIGHUP

# Cancel any changes to the working tree that are not going to be committed
git diff > "$PATCH_FILE"
git checkout -- .

git_cached_js_files=$(git diff --cached --name-only --diff-filter=ACMR | grep -e '\.js$' --color=never | xargs echo)
if [ "$git_cached_js_files" ]; then
    $NPM_BIN/jshint $git_cached_js_files || exit 1
    $NPM_BIN/jscs $git_cached_js_files || exit 1
fi

git_cached_css_files=$(git diff --cached --name-only --diff-filter=ACMR | grep -e '\.css$' --color=never | xargs echo)
if [ "$git_cached_css_files" ]; then
    $NPM_BIN/cssl -q $git_cached_css_files || exit 1
fi
