#!/bin/sh

# $1 is the path to a commit message file
# $2 is the source of the commit message (message, template, merge, squash, commit)

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3

# Exit if a rebase is in progress
GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
if [ -n "$GIT_DIR" ]; then
  if [ -d "$GIT_DIR/rebase-merge" ] || [ -d "$GIT_DIR/rebase-apply" ]; then
    exit 0
  fi
fi

# Exit 0 if aiautocommit does not exist
# This can happen if another system, with a shell which does not load ~/.zshrc and friends,
# attempts to commit.
if ! command -v aiautocommit >/dev/null 2>&1; then
  exit 0
fi

# Only run aiautocommit if there is no specific source (i.e. normal git commit).
# This prevents overwriting manual messages (-m), merge messages, etc.
if [ -n "$COMMIT_SOURCE" ]; then
  exit 0
fi

aiautocommit commit --output-file "$COMMIT_MSG_FILE"
