#!/bin/bash

# Add local user:
# Either use the LOCAL_USER_ID if passed in at runtime or
# check if external UID already exists in DOCKER container

elementIn () {
  local e match="$1"
  shift
  for e; do [[ "$e" == "$match" ]] && return 0; done
  return 1
}

if [ -z ${LOCAL_USER_ID+x} ]
then
  echo "LOCAL_USER_ID is unset"
  USER_ID=$(id -u $USER)
else
  echo "LOCAL_USER_ID is set to '$LOCAL_USER_ID'"
  USER_ID=$LOCAL_USER_ID
fi

dockerUIDs=($(cut -d: -f3 /etc/passwd))

if elementIn "$USER_ID" "${dockerUIDs[@]}"
then
  echo "Starting with DOCKER UID : $USER_ID"
else
  echo "Creating new DOCKER User with UID : $USER_ID"
  useradd --shell /bin/bash --uid $USER_ID --non-unique --comment "" --create-home user --skel /root
  export HOME=/home/user
fi

# Execute Target as User
exec /usr/sbin/gosu user:user /bin/bash -l -c "python /AQUAMIS/aquamis.py --docker $HOST_PATH $*"