#!/usr/bin/env bash

# Leave if GrumPHP ain't installed.
if [[ ! -x vendor/bin/grumphp ]]; then
  exit 0
fi

# Get the git user, email and commit message file.
GIT_USER=$(git config user.name)
GIT_EMAIL=$(git config user.email)

# Fetch the git diff and format it as command input.
DIFF=$(git -c diff.mnemonicprefix=false -c diff.noprefix=false --no-pager diff -r -p -m -M --full-index --no-color --staged | cat)

# Get the web container name.
CONTAINER=$(cat .ddev/.ddev-docker-compose-full.yaml | grep ' container_name: ddev-.*-web$' | tr -s ' ' | cut -d ' ' -f 3)

# Copy the commit message to the .git directory.
cp $1 .git/COMMIT_MSG_TMP

# Run GrumPHP.
docker exec -e GIT_USER -e GIT_EMAIL -e COMMIT_MSG_FILE -e DIFF -i $CONTAINER bash <<'COMMAND'
  (cd "./" && printf "%s\n" "$DIFF" | vendor/bin/grumphp git:commit-msg --git-user="$GIT_USER" --git-email="$GIT_EMAIL" .git/COMMIT_MSG_TMP && rm .git/COMMIT_MSG_TMP)
COMMAND
