#!/usr/bin/env bash

# Git hook: post-checkout
# Automatically copies .env when creating a new worktree
# This hook runs after git checkout, including after worktree creation

prev_head=$1
new_head=$2
branch_checkout=$3

# Only run for branch checkouts (worktree creation)
if [ "$branch_checkout" = "1" ]; then
  # Check if we're in a worktree (not the main repo)
  if git rev-parse --git-common-dir > /dev/null 2>&1; then
    git_common_dir=$(git rev-parse --git-common-dir)
    git_dir=$(git rev-parse --git-dir)

    # If git-common-dir differs from git-dir, we're in a worktree
    if [ "$git_common_dir" != "$git_dir" ]; then
      # Get the main worktree path
      main_worktree=$(dirname "$git_common_dir")

      # Copy .env from main worktree only if it doesn't already exist here
      if [ -f "$main_worktree/apps/api/.env" ] && [ ! -f "$(pwd)/apps/api/.env" ]; then
        echo "🔧 Copying .env to new worktree..."
        mkdir -p "$(pwd)/apps/api"
        cp "$main_worktree/apps/api/.env" "$(pwd)/apps/api/.env"
        echo "✓ .env copied to $(pwd)/apps/api/.env"
      fi
    fi
  fi
fi

exit 0
