# Location of this script.
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"


function remove_container()
{
  container_name=$1

  # Will be "true" if running, "false" if stopped, or "" if does not exist.
  IS_RUNNING=$(docker inspect -f '{{.State.Running}}' ${container_name} 2>/dev/null)

  if [ "$IS_RUNNING" = "true" ]; then
    docker stop $container_name -t 0
  fi

  if ! [ -z `docker ps -q -f name=${container_name}` ]; then
    echo "Removing container $container_name"
    docker rm -f -t 1 $container_name
  fi
}


function start_container()
{
  image_name=$1
  container_name=$2

  # Open up xhost (for display) only to the container.
  xhost +local:`docker inspect --format='{{ .Config.Hostname }}' $container_name`

  if [ -z `docker ps -a -q -f name=^/${container_name}$` ]; then
    # If the container does not exist, start it.
    echo "Starting new container"

    # Maping /tmp/.X11-unix allows graphics to be passed.
    docker run --rm -dt \
      --privileged \
      --network="host" \
      --workdir "$HOME" \
      --gpus all \
      -e "DISPLAY" \
      -e "HOME" \
      -v "/tmp/.X11-unix:/tmp/.X11-unix" \
      -v "$DIR/../:$HOME/adapt/adapt_ros_ws" \
      -v "$DIR/../../models/:$HOME/adapt/models" \
      --name $container_name \
      $image_name \
      /bin/bash
  elif [ -z `docker ps -q -f name=${container_name}` ]; then
    # If the container exists but is stopped, start it.
    echo "Container is stopped, restarting it"
    docker start $container_name
  else
    echo "Container already running"
  fi
}
