#!/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"
  uid=$(id -u $USER)
else
  echo "LOCAL_USER_ID is set to '$LOCAL_USER_ID'"
  uid=$LOCAL_USER_ID
fi

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

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

# Activate micromamba environment
source /usr/local/bin/_activate_current_env.sh

# Execute Target as User
exec /usr/sbin/gosu $uname:$uname "$@"
