#!/bin/bash

# A pre-commit hook script to:
#  - run linting and formatting on staged files based on the lint-staged,
#    prettier and eslint configurations in src/node/desktop.
# This script will run all applicable hooks and fails the commit afterwards if any of the hooks fail.

color_error='\033[1;31m' # red
color_highlight='\033[1;95m' # magenta
color_none='\033[0m' # no color
repo_root=$(git rev-parse --show-toplevel)

fail_precommit=false # will be set to true if the pre-commit hook should fail at the end

hook_setup() {
    cd "$repo_root"
    # Print a separator line before the output of each hook
    echo -e "${color_highlight}------${color_none}"
}

precommit_exit() {
    hook_setup
    if [ "$fail_precommit" = true ]; then
        echo -e >&2 "${color_error}pre-commit hook failed.${color_none}"
        exit 1
    else
        echo -e "${color_highlight}pre-commit hook complete.${color_none}"
        exit 0
    fi
}

echo -e "${color_highlight}Running pre-commit hook...${color_none}"

#####################################
#          Add hooks below          #
#####################################

# Linting and formatting on RStudio Desktop IDE files
if git diff --staged --name-only | grep -qE '^src/node/desktop/.*'
then
    if ! test -f ./src/node/desktop/.lintstagedrc; then
        echo -e >&2 "${color_highlight}Note: src/node/desktop linting pre-commit hook is not being run because ${color_none}.lintstagedrc${color_highlight} was not found.${color_none}"
    elif ! test -x ./src/node/desktop/node_modules/.bin/prettier || ! test -x ./src/node/desktop/node_modules/.bin/eslint; then
        echo -e >&2 "${color_highlight}Note: src/node/desktop linting pre-commit hook is not being run because the npm packages are not installed.${color_none}"
        echo -e >&2 "\tInstall the npm dependencies by moving to ${color_highlight}src/node/desktop${color_none} and running ${color_highlight}npm install${color_none}."
    else
        hook_setup
        cd ./src/node/desktop && npx lint-staged
        if [ $? -ne 0 ]; then
            fail_precommit=true
        fi
    fi
fi

#####################################
#          Add hooks above          #
#####################################

# This should be the last line of this file
precommit_exit
