#!/bin/sh
# Prepare the dev environment for a new checkout or worktree.
#
# Installed into the git hooks directory by script/setup.py. Deliberately tiny
# and self-contained: it stays valid on branches where the setup script does not
# exist, and simply does nothing there.

# $3 is 1 for a branch checkout, 0 for a file checkout.
[ "$3" = "1" ] || exit 0

top=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0

# This also runs on ordinary branch switches, where there is nothing to do. Both
# layouts are checked because git for Windows runs hooks under its own bundled
# shell, where the environment lives in venv/Scripts rather than venv/bin.
[ -x "$top/venv/bin/python" ] && exit 0
[ -f "$top/venv/Scripts/python.exe" ] && exit 0

[ -f "$top/script/setup.py" ] || exit 0

# Clear VIRTUAL_ENV so a checkout made from a shell with an environment already
# activated still gets its own, rather than having the active one repointed at
# this working tree.
unset VIRTUAL_ENV

# The interpreter goes by different names across platforms, and on Windows
# "python3" is often a stub that opens the app store instead of running
# anything, so each candidate is tried before it is used. Doing nothing is the
# right outcome when none of them work.
try_setup() {
  "$@" -c "" >/dev/null 2>&1 || return 1
  exec "$@" "$top/script/setup.py"
}

try_setup python3
try_setup python
try_setup py -3
exit 0
