#!/bin/sh -eu

if [ ! -d .git/hooks ]; then
  echo "Error: Please run this script from the root of the repository."
  exit 1;
fi

# Resolve PHP cmd.
prestaDir=/var/www/html
moduleDir=${prestaDir}/modules/resursbank
phpCmd="docker compose exec -w ${moduleDir} -T "

echo "--==( Setting up git pre-commit hook )==--"

# Create git pre-commit hook file.
HOOK_FILE=".git/hooks/pre-commit"

if [ -f $HOOK_FILE ]; then
  rm -f $HOOK_FILE
fi

touch $HOOK_FILE
chmod +x $HOOK_FILE

cat <<EOT >> $HOOK_FILE
#!/usr/bin/env -S bash

ERRORS=0

for file in \$(git diff --name-only --cached)
do
    currentDirectory=\$(pwd)
    cd $PWD
    if $phpCmd test -f "$moduleDir/\$file"; then
        SRC_FILES="\$SRC_FILES $moduleDir/\$file"
    fi
    cd \$currentDirectory
done

echo "==========================================================="
echo "#                  SCANNING SOURCE FILES                  #"
echo "==========================================================="

if [ -n "\$SRC_FILES" ]; then
    echo "---==( Executing PHPCS for affected files. )==---"
    currentDirectory=\$(pwd)
    cd $PWD
    if ! $phpCmd $prestaDir/vendor/bin/phpcs --extensions=php,phtml --standard=PSR12 \$SRC_FILES; then
        ERRORS=1
    fi
    cd \$currentDirectory
fi

if [ "\${ERRORS}" = "1" ]; then
    exec < /dev/tty
    read -p "Continue commit despite remaining errors? (y/n)?" continueCommit
    case "\$continueCommit" in
        y|Y ) exit 0;;
        * ) echo "Aborting."; exit 1;;
    esac
fi
EOT

echo OK
exit 0
