#!/bin/bash
set -e -x

# Setting up paths to where everything is/will be
AGRUM_DIR=$CI_PROJECT_DIR
PYAGRUM_DIR=${AGRUM_DIR}/wrappers/pyAgrum
WHEELHOUSE_DIR=${AGRUM_DIR}/wheelhouse

# Downloading aGrUM and initializing the wheelhouse dir
mkdir -p ${WHEELHOUSE_DIR}/pyAgrum
cp -R ${PYAGRUM_DIR} ${WHEELHOUSE_DIR}/pyAgrum/
cp ${AGRUM_DIR}/wrappers/swig/* ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum

# Extracting pyAgrum version from VERSION.txt
MAJOR=$(cat ${AGRUM_DIR}/VERSION.txt | grep AGRUM_VERSION_MAJOR | sed 's/set(AGRUM_VERSION_MAJOR "\(.*\)")/\1/')
MINOR=$(cat ${AGRUM_DIR}/VERSION.txt | grep AGRUM_VERSION_MINOR | sed 's/set(AGRUM_VERSION_MINOR "\(.*\)")/\1/')
PATCH=$(cat ${AGRUM_DIR}/VERSION.txt | grep 'set(AGRUM_VERSION_PATCH' | sed 's/set(AGRUM_VERSION_PATCH "\(.*\)")/\1/' | grep -v AGRUM_VERSION_PATCH)

if [ -z $MAJOR ]
then
  echo "Could not find aGrUM's MAJOR version number."
  exit 1
elif [ -z $MINOR ]
then
  echo "Could not find aGrUM's MINOR version number."
  exit 1
elif [ -z $PATCH ]
then
  echo "Could not find aGrUM's PATCH version number."
  exit 1
fi

PYAGRUM_VERSION="${MAJOR}.${MINOR}.${PATCH}"

# Doing cmake work for the moment
sed 's/@PYAGRUM_VERSION@/'${PYAGRUM_VERSION}'/' \
  < ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum/cmake/setup.in.py \
  > ${WHEELHOUSE_DIR}/pyAgrum/setup.py

sed 's/@PYAGRUM_VERSION@/'${PYAGRUM_VERSION}'/' \
  < ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum/cmake/functions.in.py \
  > ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum/functions.py

sed 's/@PYAGRUM_VERSION@/'${PYAGRUM_VERSION}'/' \
  < ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum/cmake/__init__.in.py \
  > ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum/__init__.py

cp ${PYAGRUM_DIR}/wheelhouse/files/* ${WHEELHOUSE_DIR}/pyAgrum/

# Removing unecessary files from the wheelhouse
rm -rf ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum/cmake
rm -rf ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum/generated-files*
rm -rf ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum/wheelhouse
rm -rf ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum/sphinx
rm -rf ${WHEELHOUSE_DIR}/pyAgrum/pyAgrum/testunits

# Compile and install aGrUM
cd ${AGRUM_DIR}
/opt/python/cp36-cp36m/bin/python act install release aGrUM --withoutSQL --no-fun -d /usr
cd -

cd ${WHEELHOUSE_DIR}/pyAgrum
# Compile wheels
for PYBIN in /opt/python/*/bin
do
  rm -rf ${WHEELHOUSE_DIR}/pyAgrum/build
  "${PYBIN}/python" ${WHEELHOUSE_DIR}/pyAgrum/setup.py sdist
  "${PYBIN}/python" ${WHEELHOUSE_DIR}/pyAgrum/setup.py bdist_wheel
done
cd -

# Bundle external shared libraries into the wheels
for whl in ${WHEELHOUSE_DIR}/pyAgrum/dist/*.whl
do
  auditwheel repair "$whl" -w ${WHEELHOUSE_DIR}
done

# Moves wheels in shared Volume if exists
cd ${WHEELHOUSE_DIR}
ls -1 | grep -v "manylinux1" | xargs rm -rf
ls -1 | grep "numpy" | xargs rm -rf
cd -

