#!/usr/bin/env bash
set -euo pipefail

if [ "${1-""}" == "" ]; then
    DIR="default"
    PROJECT="$BUILD_WORKSPACE_DIRECTORY/carmaker"
else
    DIR="pools"
    PROJECT="$1"
fi
echo "Project folder: $PROJECT"

if [ "$DIR" == "pools" ]; then
    echo "#INFOFILE1.1 - Do not remove this line!
    FileIdent = CarMaker-Project 9
    FileCreator = CarMaker 9.1 2021-02-16
    Create = 1523632931
    Update.CM = 9.1 1607636439
    DataPool.Shared = $BUILD_WORKSPACE_DIRECTORY/carmaker
    DataPool.Shared2 =" > "$PROJECT/Data/Config/Project"

    # TODO - Work with CM to find a better solution for plugins in dropdowns
    # reference plugin file from where vehicle resides
    if [ "$PROJECT" != "$BUILD_WORKSPACE_DIRECTORY/carmaker" ]; then
        cp "$BUILD_WORKSPACE_DIRECTORY/carmaker/Data/Config/Plugins" "$PROJECT/Data/Config/Plugins"
        cp "$BUILD_WORKSPACE_DIRECTORY/carmaker/zoox.tcl" "$PROJECT/zoox.tcl"
    fi
else
    echo "#INFOFILE1.1 - Do not remove this line!
    FileIdent = CarMaker-Project 9
    FileCreator = CarMaker 9.1 2021-02-16
    Create = 1523632931
    Update.CM = 9.1 1607636439
    DataPool.Shared =
    DataPool.Shared2 =" > "$PROJECT/Data/Config/Project"
fi

export CM_PROJECT_FOLDER=$PROJECT
export CM_BASE_DIRECTORY=$BUILD_WORKSPACE_DIRECTORY
# Get bazel path to carmaker solver
SOLVERPATH="$(readlink -f carmaker/carmaker_solver_private.linux64)"
# Get path to bazel IPG folder
CMPATH="$(readlink -f ../ipg/carmaker/linux64-9.1/bin/CM)"
# Remove the part of the path after the ipg folder
IPGPATH="${CMPATH%/carmaker/linux64-9.1/bin/*}"
# Set IPGHome environment variable to match bazel path
export IPGHOME=$IPGPATH
# Launch bazel copy of CM (launch gui)
../ipg/carmaker/linux64-9.1/bin/CM -appl $SOLVERPATH $PROJECT -cmd "source $PROJECT/zoox.tcl"
