#!/usr/bin/env bash

# This bootstrap scripts set up the build environment for TimescaleDB
# Any flags will be passed on to CMake, e.g.,
# ./bootstrap -DCMAKE_BUILD_TYPE="Debug"

## Check to make cmake is installed
if ! command -v cmake >/dev/null 2>&1; then
	echo "cmake is required to build TimescaleDB. Please install via your system's preferred method."
	exit 1
fi

BUILD_DIR=${BUILD_DIR:-./build}
BUILD_FORCE_REMOVE=${BUILD_FORCE_REMOVE:-false}
SRC_DIR=$(dirname $0)
if [[ ! ${SRC_DIR} == /* ]]; then
    SRC_DIR=$(pwd)/${SRC_DIR}
fi

if [ ${BUILD_FORCE_REMOVE} == "true" ]; then
    rm -fr ${BUILD_DIR}
elif [ -d ${BUILD_DIR} ]; then
    echo "Build system already initialized in ${BUILD_DIR}"

    read -r -n 1 -p "Do you want to remove it (this is IMMEDIATE and PERMANENT), y/n? " choice
    echo ""
    if [ $choice == "y" ]; then
        rm -fr ${BUILD_DIR}
    else
        exit
    fi
fi

set -e
set -u

mkdir -p ${BUILD_DIR} && \
    cd ${BUILD_DIR} && \
    cmake ${SRC_DIR} "$@"

echo "TimescaleDB build system initialized in ${BUILD_DIR}. To compile, do:"
echo -e "\033[1mcd ${BUILD_DIR} && make\033[0m"