#!/bin/bash

# abort script on any command that exits with a non zero value
set -e
set -u

PATH=/var/vcap/packages/node/bin:/var/vcap/packages/python/bin:$PATH

PYTHONLIBS=${BOSH_INSTALL_TARGET}/backuprestore/service_fabrik_backup_restore/dependencies
SOURCES_PATH=${BOSH_INSTALL_TARGET}/backuprestore/service_fabrik_backup_restore/dependencies_sources

# Copy the 'blueprint-service' directory from /src/ to the installation target of this release
echo "Copying blueprint service files..."
cp -a ${BOSH_COMPILE_TARGET}/blueprint-service/* ${BOSH_INSTALL_TARGET}/

# Install npm dependencies
echo "Rebuild NPM dependencies..."
cd ${BOSH_INSTALL_TARGET}
npm rebuild

PIP_CMD=/var/vcap/packages/python/bin/pip3

# Download production dependencies
cd /var/vcap/packages/blueprint/backuprestore/service_fabrik_backup_restore
$PIP_CMD download --dest=./dependencies_sources -r requirements.txt

# Install python dependencies
cd ${SOURCES_PATH}
mkdir ${PYTHONLIBS}

# install pbr package first
pip3 install --target=${PYTHONLIBS} * --no-index --find-links=file://${SOURCES_PATH} --ignore-installed
# Remove python2 backport module 'futures'
# In python 3, the functionalities of 'futures' are builtin. As the python-swiftclient package is compatiable for both
#   python2 and python3, it lists 'futures' in its dependencies list. We have to delete it to prevent python from using
#   the functionalities of this module which are incompatible with python3 itself.
# Unfortunately, pip has no mechanism to uninstall a package from a specific directory. Thus, we have to delete it manually.
rm -rf ${PYTHONLIBS}/concurrent
rm -rf ${PYTHONLIBS}/futures*

# Remove dependency sources
rm -rf ${SOURCES_PATH}
