#!/usr/bin/env bash

BUILD_DIR=$PWD
if [ -z "$WORKSPACE_DIR" ]; then
    echo "Workspace is not defined. Add WORKSPACE_DIR to environment"
    exit 1
fi

BUILD_DIR=${BUILD_DIR//$WORKSPACE_DIR/\/workspace}
if [ -n "$VAR_SPECFILE" ]; then
    VAR_SPECFILE=${VAR_SPECFILE/$WORKSPACE_DIR/\/workspace}
fi

if [ -d .cmake/api/v1/query ]; then
    rm -rf .cmake/api/v1/query
fi

if [[ "$OSTYPE" == "darwin"* ]]; then
    export PATH="/usr/local/bin:/Applications/Docker.app/Contents/Resources/bin:~/.docker/bin:$PATH"
fi

touch .env.list
docker run -i --rm -h `hostname` $($(dirname "${BASH_SOURCE[0]}")/get-user-id-for-docker) --env-file .env.list -v "${WORKSPACE_DIR}":/workspace -w "${BUILD_DIR}" @docker_image_tag@ apptool "$@" ${VAR_SPECFILE:+--specfile "${VAR_SPECFILE}"}

if [ -f QtCreatorDeployment.txt ]; then
    sed -i -- "s#/workspace#${WORKSPACE_DIR}#g" QtCreatorDeployment.txt
fi
