#!/bin/sh

echo "[HOOK] post-checkout запущен"

old_ref=$1
new_ref=$2
is_branch_checkout=$3

if [ "$is_branch_checkout" -ne 1 ]; then
  echo "[HOOK] Не ветка — пропускаем"
  exit 0
fi

checkout_entry=$(git reflog --format='%gs' -n5 | grep -E '^checkout: moving' | head -n1)

if echo "$checkout_entry" | grep -q 'from'; then
  old_branch=$(echo "$checkout_entry" | sed -E 's/^checkout: moving from ([^ ]+) to .*$/\1/')
  new_branch=$(echo "$checkout_entry" | sed -E 's/^checkout: moving from .* to ([^ ]+)$/\1/')
else
  old_branch="(detached)"
  new_branch=$(echo "$checkout_entry" | sed -E 's/^checkout: moving to ([^ ]+)$/\1/')
fi

[ -z "$old_branch" ] && old_branch="(unknown)"
[ -z "$new_branch" ] && new_branch="(unknown)"

echo "Switched from $old_branch to $new_branch"

hook_dir=$(dirname "$0")
ps1_script=$(cd "$hook_dir" && pwd -W)/post-checkout.ps1

powershell.exe -ExecutionPolicy Bypass -File "$ps1_script" -oldBranch "$old_branch" -newBranch "$new_branch" 
code=$?

if [ "$code" -ne 0 ]; then
  echo "[HOOK] Ошибка при переключении ветки (exit code $code)"
  exit 1
fi

echo "[HOOK] Выполнено успешно"
exit 0