#!/bin/sh
# ### git commit message template ###
git config commit.template .git/templatemessage
TICKETID=`git rev-parse --abbrev-ref HEAD | LC_ALL=en_US.utf8 grep -oP '^((copilot\/)?(feature|bug|bugfix|fix|hotfix|task|chore)\/)?\K\d{1,7}' || true`
if [ -z "$TICKETID" ]
then
  TICKETID="0"
fi
TEMPLATE="#$TICKETID: "
echo "[POST-CHECKOUT] Setting template commit to '$TEMPLATE'"
# wrap $TEMPLATE in quotes or else it is trimmed automatically
echo "$TEMPLATE" > ".git/templatemessage"


if [ "${SKIP_HOOKS:-0}" -gt 0 ] 2>/dev/null; then
  echo "[POST-CHECKOUT] skipping hooks ($SKIP_HOOKS)"
  exit 0
fi

# ### run npm install ###
echo "[POST-CHECKOUT] 📦 Checking for changes to dependencies"
# $1 is the new HEAD pointer
NEWHEAD=$1
# $2 is the previous HEAD pointer
OLDHEAD=$2
# extract all paths to package-lock.json files
PACKAGES=$(git diff --name-only "$OLDHEAD" "$NEWHEAD" | grep -E "^package-lock\.json" || true)

if [ -n "$PACKAGES" ]; then
  for package in $PACKAGES; do
    echo "📦 $package was changed."
  done
  echo "📦 Running npm install to update your dependencies..."
  npm install
  npm run lint:fix
else
  echo "📦 All packages up-to-date. No need to run npm install."
fi
