#!/bin/bash

set -euo pipefail

STAGED=$(git diff --name-only --cached --diff-filter=d)
JS="$(echo $(grep ".*\.js$" <<< "$STAGED" || true))"
PHP="$(echo $(grep ".*\.php$" <<< "$STAGED" || true))"
CSS="$(echo $(grep ".*\.scss$" <<< "$STAGED" || true))"
TWIG="$(echo $(grep ".*\.twig$" <<< "$STAGED" || true))"

if [ -z "$JS" ] && [ -z "$PHP" ] && [ -z "$CSS" ] && [ -z "$TWIG" ]; then
    exit 0
fi

if ! docker compose ps web > /dev/null 2>&1; then
    echo "The web container isn't running, but we need it for linting."
    echo "Start the web container or commit with --no-verify."
    exit 1
fi

if [ -n "$TWIG" ]; then
    echo "Linting Twig"
    for t in $TWIG
    do
        if ! git grep -qc "${t/templates\//}"; then
            echo "$t not referenced in codebase"
            exit 1
        fi
    done
    docker compose exec -T web bin/twig-parse $TWIG
fi

if [ -n "$JS" ]; then
    echo "Linting JS"
    docker compose exec -T web npx eslint -c misc/eslint.config.mjs --no-warn-ignored $JS
fi

if [ -n "$CSS" ]; then
    echo "Linting CSS"
    docker compose exec -T web npx stylelint --config misc/stylelint.json --cache --cache-location cache/stylelint $CSS
fi

if [ -n "$PHP" ]; then
    echo "Linting PHP"
    docker compose exec -T web sh -c \
        "php -l $PHP && vendor/bin/phpcs $PHP && vendor/bin/phpstan analyze --no-progress --configuration=misc/phpstan.neon --memory-limit 512M $PHP"
fi
