#! /bin/bash

echo
echo "#"
echo "# setting up build environment"
echo "#"
echo

# compiler settings
export CC=clang-omp
export CXX=clang-omp++
export PyVer=`python3 -V | python3 -c 'import sys; print (".".join(sys.stdin.readline().split()[1].split(".")[:2]))'`
export UTSUSEMI_REV=1037
export NUM_MULTH=8

# paths
export ROOT=`pwd`
export SOURCETREE=src
export BUILD=${ROOT}/mlf_build_root
export BUILDLOG=${BUILD}.log
export PY3LIB=${BUILD}/opt/mlfsoft/python${PyVer}
export PYENV=${BUILD}/opt/mlfsoft/python${PyVer}/python
export MANYO_PATH=${PY3LIB}/manyo
export UGAO0_PATH=${PY3LIB}/python-ugao
export UTSU0_PATH=${PY3LIB}/python-utsusemi
export UGAO_PATH=${PY3LIB}/python-ugao/uGao
export UTSU_PATH=${PY3LIB}/python-utsusemi/utsusemi
export UTIL_PATH=${PY3LIB}/util
export INSTALL_PATH=${MANYO_PATH}

# python libs/includes

export PYBIN=`which python${PyVer}`
export NUMPYLIB=`echo $PYBIN | sed 's|bin/python|lib/python|g'`
export NUMPYINC=${NUMPYLIB}/site-packages/numpy/core/include
export PYPATH=`python3-config --includes | tr " " "\n" | cut -c 3- | xargs | tr " " ":"`
export PYLIBS=`python3-config --includes | tr " " "\n" | cut -c 3- | awk -F"/include" '{print $1"/lib"}' | xargs | tr " " ":"`

if [[ -a ${NUMPYINC} ]]
then
    echo "numpy found"
else
    echo "need python3 installation with numpy in standard location (eg brew install python3 numpy)"
    exit
fi

echo PYBIN $PYBIN
echo PYPATH $PYPATH
echo PYLIBS $PYLIBS
echo NUMPY $NUMPYLIB $NUMPYINC

#
# cp src
#

echo
echo "source:  ${SOURCETREE}"
echo "build:   ${BUILD}"
echo "logfile: ${BUILDLOG}"
echo

echo
echo "#"
echo "# erasing old build ${BUILD} in 3s"
echo "#"
echo


sleep 3

rm ${BUILDLOG}
touch ${BUILDLOG}

echo
echo rm old build
echo

rm -rf ${BUILD}

echo
echo copy source tree
echo

cp -R ${SOURCETREE} ${BUILD}

cd ${ROOT}

# make file envs
export INC_EXT="Manyo MLF Utsusemi "
export C_INCLUDE_PATH=/usr/local/include/nexus:/usr/include/hdf5/serial:${MANYO_PATH}/include:/usr/local/include:${MANYO_PATH}/include/Manyo:${MANYO_PATH}/include/MLF:${MANYO_PATH}/include/Utsusemi:${PYPATH}:${NUMPYLIB}/site-packages/numpy/core/include
export LIBRARY_PATH=${MANYO_PATH}/lib:${INSTALL_PATH}:/usr/local/lib:${PYLIBS}
export LD_LIBRARY_PATH=${LIBRARY_PATH}:/usr/local/opt/python3/lib:${PYLIBS}
export PATH=${MANYO_PATH}/bin:${PATH}
export CPLUS_INCLUDE_PATH=${C_INCLUDE_PATH}

echo
echo "#"
echo "# starting build"
echo "#"
echo

# build
echo manyo
cd ${BUILD}/manyo
make  -f Makefile.mac install -j #>> ${BUILDLOG} 2>&1

cd ${BUILD}
cp ../fix*.sh .

echo
echo "#"
echo "# fix imports"
echo "#"
echo

./fix_imports_manyo.sh manyo

echo
echo "BUILD COMPLETE: ${BUILD}"
echo

