#!/bin/sh

#
# Run the hook command.
# Note: this will be replaced by the real command during copy.
#

GIT_USER=$(git config user.name)
GIT_EMAIL=$(git config user.email)

# Fetch the commit message
COMMIT_MSG_FILE=$1
COMMIT_MSG=$(cat "${COMMIT_MSG_FILE}")

# Fetch the GIT diff and format it as command input:
DIFF=$(git diff -r -p -m -M --full-index --staged | cat)

# Copy the commit message and run GrumPHP
vagrant ssh --command '$(which sh)' << COMMANDS

  # Transfer the DIFF
  DIFF=\$(cat <<- '__GRUMPHP_DIFF_HEREDOC__'
	${DIFF}
	__GRUMPHP_DIFF_HEREDOC__
  )

  # Transfer the commit message
  COMMIT_MSG=\$(cat <<- '__GRUMPHP_COMMIT_MSG_HEREDOC__'
	${COMMIT_MSG}
	__GRUMPHP_COMMIT_MSG_HEREDOC__
  )

  VAGRANT_COMMIT_MSG_FILE=\$(mktemp -t "grumphp-commitmsg.XXXXXXXXXX")
  echo "\${COMMIT_MSG}" > \$VAGRANT_COMMIT_MSG_FILE
  printf "%s\n" "\${DIFF}" | exec $(HOOK_COMMAND) '--ansi' --git-user='$GIT_USER' --git-email='$GIT_EMAIL' \$VAGRANT_COMMIT_MSG_FILE
  RC=\$?
  rm \$VAGRANT_COMMIT_MSG_FILE
  exit \$RC
COMMANDS
