#! /usr/bin/env bash
set -e

echo "You have chosen to isntall neovim from source."

# If ~/src/neovim doesn't exist, clone a fresh copy
cd ~/src
if [ ! -d ~/src/neovim ]; then
    git clone https://github.com/neovim/neovim
fi
cd neovim

# Handle branch checkout
echo "Do you want to switch to the stable branch? (y/n)"
read -r -n 1 response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
    git checkout stable
fi

# Figure out the appropriate make command. 
if [ -x "$(command -v gmake)" ]; then
    MAKE_CMD=gmake
else
    MAKE_CMD=make
fi

# Determine the install prefix
NVIM_INSTALL_PREFIX=${NVIM_INSTALL_PREFIX:-$HOME/.local}

# Build
echo "Building neovim..."
$MAKE_CMD CMAKE_BUILD_TYPE=Release CMAKE_EXTRA_FLAGS="-DCMAKE_INSTALL_PREFIX=$NVIM_INSTALL_PREFIX"

# Install
echo "Would you like to install neovim? (y/n)"
read -r -n 1 response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
    $MAKE_CMD install
fi