#!/bin/bash

PROJECT=kicad-utils

set -e

CMAKE=`which cmake 2>/dev/null`
PREFIX=$HOME/opt/$PROJECT
# TODO: find basedir from the current binary
BASEDIR=`pwd`

if [ ! -x "$CMAKE" ]
then
    echo "cmake is not installed"
    exit 1
fi

cd $BASEDIR

NEW=`test -d build && echo 1 || true`

git submodule init
git submodule sync
git submodule update

if [[ ! -d thirdparty/antlr4/runtime/Cpp/build ]]
then
  cd thirdparty/antlr4
  mvn install
  cd runtime/Cpp/build
  mkdir thirdparty/antlr4/runtime/Cpp/build
  cmake .. -DCMAKE_INSTALL_PREFIX=$HOME/opt/antlr4-cpp
  make install -j8
fi

mkdir -p build

CMAKE_OPTS=()
CMAKE_OPTS+=(-DCMAKE_INSTALL_PREFIX=$PREFIX)
#CMAKE_OPTS+=(-DCMAKE_SKIP_RPATH=NO)
#CMAKE_OPTS+=(-DCMAKE_SKIP_INSTALL_RPATH=NO)
# These are required until Antlr C++ is installed by the system
CMAKE_OPTS+=(-DCMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE)
CMAKE_OPTS+=(-DAntlr4_DIR=$HOME/opt/antlr4-cpp/lib/cmake/Antlr4)

cd build
echo ""
echo "Generating build.."
echo ""
cmake "${CMAKE_OPTS[@]}" ..


echo ""
echo ""
echo ""

if [[ $NEW == 1 ]]
then
    echo "Reusing existing build/ directory. You should probably run cd build && make clean"
else
    echo "The build files are generated in build/. To build run: cd build && make install"
    echo "The binaries will be installed under $PREFIX"
fi

echo ""