#!/bin/bash
# This is invoked from the Buildings directory.
# Hence, we need to share one level up
cur_dir=`pwd`
bas_nam=`basename ${cur_dir}`
sha_dir=`dirname ${cur_dir}`


# Function declarations
function create_mount_command()
{
   local pat="$1"
   # Each entry in pat will be a mounted read-only volume
   local mnt_cmd=""
   for ele in ${pat//:/ }; do
      mnt_cmd="${mnt_cmd} -v ${ele}:/mnt${ele}:ro"
   done

   # On Darwin, the exported temporary folder needs to be /private/var/folders, not /var/folders
   # see https://askubuntu.com/questions/600018/how-to-display-the-paths-in-path-separately
   if [ `uname` == "Darwin" ]; then
       mnt_cmd=`echo ${mnt_cmd} | sed -e 's| /var/folders/| /private/var/folders/|g'`
   fi
   echo "${mnt_cmd}"
}

function update_path_variable()
{
  # Prepend /mnt/ in front of each entry of a PATH variable in which the arguments are
  # separated by a colon ":"
  # This allows for example to create the new MODELICAPATH
  local pat="$1"
  local new_pat=`(set -f; IFS=:; printf "/mnt%s:" ${pat})`
  # Cut the trailing ':'
  new_pat=${new_pat%?}
  echo "${new_pat}"
}

# Export the MODELICAPATH
if [ -z ${MODELICAPATH+x} ]; then
    MODELICAPATH=`pwd`
else
    # Add the current directory to the front of the Modelica path.
    # This will export the directory to the docker.
    MODELICAPATH=`pwd`:${MODELICAPATH}
fi

# Create the command to mount all directories in read-only mode
# a) for MODELICAPATH
MOD_MOUNT=`create_mount_command ${MODELICAPATH}`

# Prepend /mnt/ in front of each entry, which will then be used as the MODELICAPATH
DOCKER_MODELICAPATH=`update_path_variable ${MODELICAPATH}`


# If the current directory is part of the argument list,
# replace it with . as the docker may have a different file structure
arg_lis=`echo $@ | sed -e "s|${cur_dir}|.|g"`
docker run \
  --user=${UID} \
  --mac-address=${MAC_ADDRESS} \
  -v /tmp/.X11-unix:/tmp/.X11-unix \
  -e DISPLAY=${DISPLAY} \
  --detach=false \
  --rm \
  ${MOD_MOUNT} \
  -v ${sha_dir}:/mnt/shared \
  ${DOCKER_REPONAME}/${DYMOLA_VERSION} /bin/bash -c \
  "export MODELICAPATH=${DOCKER_MODELICAPATH} && \
  cd /mnt/shared/${bas_nam} && \
  dymola ${arg_lis}"
