#!/bin/bash

# Check if there are unstaged changes
if git diff --quiet; then
    echo -e "No unstaged changes to stash...\n"
    STASH_CREATED=false
else
    # Unstaged changes detected
    git stash --keep-index -u
    echo -e "Stashing unstaged changes...\n"
    STASH_CREATED=true
fi

# Find all changed files for this commit
# Compute the diff only once to save a small amount of time.
CHANGED_FILES=$(git diff --name-only --cached --diff-filter=ACMR)
# Get only changed files that match our file suffix pattern
get_pattern_files() {
    pattern=$(echo "$*" | sed "s/ /\$\\\|/g")
    echo "$CHANGED_FILES" | { grep "$pattern$" || true; }
}
# Get all changed python files
PY_FILES=$(get_pattern_files .py)
JS_FILES=$(get_pattern_files .js)

# Tracks if any checks fail
FAIL=0

# Git Secrets
echo "Running Git Secrets..."
./nhsd-git-secrets/pre-commit-mac.sh
if [ $? -ne 0 ]; then
    echo -e "Git Secrets failed. Commit aborted. \n"
    FAIL=1    
else
    echo -e "Git Secrets check passed.\n"
fi


# Lint JavaScript files in the sandbox folder
echo "Linting JavaScript files..."
if [[ -n "$JS_FILES" ]]; then
    node_modules/.bin/eslint 'sandbox/**/*.{js,jsx}'
    if [ $? -ne 0 ]; then
        echo -e "JavaScript linting failed. Commit aborted. \n"
        FAIL=1
    else
        echo -e "JavaScript linting passed.\n"
    fi
else
    echo -e "No JavaScript files to lint. Skipping JavaScript linting. \n"
fi


# Lint Python files in the project
echo "Linting Python files..."
if [[ -n "$PY_FILES" ]]; then
    ./scripts/lint_python.sh
    if [ $? -ne 0 ]; then
        echo -e "Python linting failed. Commit aborted. \n"
        FAIL=1
    else
        echo -e "Python linting passed.\n"
    fi
else
    echo -e "No Python files to lint. Skipping Python linting. \n"
fi

# Ensure Test Documentation Validity
echo "Ensuring test documentation validity..."
if ./scripts/ensure_docs_validity.sh > /dev/null 2>&1; then
    echo -e "Documentation check passed. \n"
else
    echo -e "Test documentation validation failed. Commit aborted. \n"
    FAIL=1
fi

# Check Licences
echo "Checking licenses..."
if ./scripts/check_licences.sh > /dev/null 2>&1; then
    echo -e "License check passed. \n"
else
    echo -e "License check failed. Commit aborted. \n"
    FAIL=1
fi

# Pop the stash only if a stash was created
if [ "$STASH_CREATED" = true ]; then
    echo "Restoring unstaged changes..."
    git stash pop -q
fi

# Exit with failure if any checks failed
if [ $FAIL -ne 0 ]; then
    exit 1
fi

echo -e "All checks passed. Proceeding with commit. \n"
exit 0
