#!/bin/bash
set -euo pipefail

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

if [ -z "$JS" ] && [ -z "$PHP" ] && [ -z "$CSS" ]; then
    echo "Nothing to reformat."
    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 reformatting."
    exit 1
fi

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

if [ -n "$PHP" ]; then
    echo "Reformatting PHP"
    docker compose exec -T web vendor/bin/phpcbf $PHP
fi

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

if [ -n "$STAGED" ]; then
    git add $STAGED
fi
