#!/bin/sh

set -eu

repo_root=$(git rev-parse --show-toplevel)
hooks_dir="$repo_root/.git/hooks"

mkdir -p "$hooks_dir"

cat >"$hooks_dir/prepare-commit-msg" <<'EOF'
#!/bin/sh

# Fill commit message from .git/CODEX_COMMIT_MSG when user commits via UI without text.

msg_file="$1"
commit_source="${2:-}"

case "$commit_source" in
  message|merge|squash)
    exit 0
    ;;
esac

# If there is already a real message line, keep it untouched.
if grep -Eq '^[[:space:]]*[^#[:space:]]' "$msg_file"; then
  exit 0
fi

codex_msg_file="$(git rev-parse --git-path CODEX_COMMIT_MSG)"

if [ -s "$codex_msg_file" ]; then
  # Take first line only to keep messages short and predictable.
  head -n 1 "$codex_msg_file" | tr -d '\r' > "$msg_file"
fi
EOF

cat >"$hooks_dir/post-commit" <<'EOF'
#!/bin/sh

# Auto-push after each successful commit.
# If no upstream exists yet, set it to origin/<current-branch>.

branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || exit 0
codex_msg_file="$(git rev-parse --git-path CODEX_COMMIT_MSG)"

if ! git remote get-url origin >/dev/null 2>&1; then
  echo "post-commit: remote 'origin' not found, skipping auto-push." >&2
  rm -f "$codex_msg_file" >/dev/null 2>&1 || true
  exit 0
fi

if git rev-parse --abbrev-ref --symbolic-full-name '@{u}' >/dev/null 2>&1; then
  git push
else
  git push --set-upstream origin "$branch"
fi

# Consume prepared Codex message after the commit.
rm -f "$codex_msg_file" >/dev/null 2>&1 || true
EOF

chmod +x "$hooks_dir/prepare-commit-msg" "$hooks_dir/post-commit"
echo "Installed git hooks in $hooks_dir"
