#!/bin/bash
# Usage: script/bootstrap
# Ensures all dependencies are installed locally.

set -e

cd "$(dirname -- "$(readlink -f -- "$0")")"/..
ROOT=$(pwd)

if [ -z "$VENV_NAME" ]; then
    VENV_NAME="env"
fi

if [ ! -d "$VENV_NAME" ]; then
    if [ -z "$VENV_PYTHON" ]; then
        VENV_PYTHON=$(command -v python3)
    fi
    "$VENV_PYTHON" -m venv "$VENV_NAME"
fi
. "$VENV_NAME/bin/activate"

# We're in the venv now, so use the first Python in $PATH. In particular, don't
# use $VENV_PYTHON - that's the Python that *created* the venv, not the python
# *inside* the venv
python -m pip install -U 'pip>=10.0.1'
python -m pip install -r requirements.txt

# Use git itself, rather than testing for a ".git" directory, so this works
# from a linked `git worktree` too (there ".git" is a file, not a directory).
if git rev-parse --git-dir >/dev/null 2>&1; then
    if [ -f ".git-blame-ignore-revs" ]; then
        echo ""
        echo "Setting blame.ignoreRevsFile to .git-blame-ingore-revs"
        git config --local blame.ignoreRevsFile .git-blame-ignore-revs
    fi

    # git-path hooks resolves to the *common* hooks dir, so this installs once
    # for the primary checkout and every worktree that shares it.
    HOOKS_DIR="$(git rev-parse --git-path hooks)"
    # Anchor the symlink to the primary checkout, not $ROOT -- in a worktree
    # $ROOT is the worktree itself, and the hooks dir is shared, so pointing
    # at $ROOT would leave a dangling symlink once that worktree is removed.
    PRIMARY_ROOT="$(cd "$(dirname -- "$(git rev-parse --git-common-dir)")" && pwd)"
    if [ ! -e "${HOOKS_DIR}/pre-commit" ]; then
        echo ""
        echo "Installing pre-commit hook"
        ln -sf "${PRIMARY_ROOT}/.git_hooks_pre-commit" "${HOOKS_DIR}/pre-commit"
    fi
fi

echo ""
echo "Run source env/bin/activate to get your shell in to the virtualenv"
echo "See README.md for more information."
echo ""
