#!/bin/sh
command -v docker >/dev/null 2>&1 || { \
        echo >&2 "docker is required but could not be found.  Aborting."; \
        echo >&2 "To setup Docker: https://docs.docker.com/engine/getstarted/step_one/"; \
        exit 1; }

novnc_help="\n
  1) open a tab in your browser at\n
      \n
         \t http://localhost:6080/\n
     \n
     (<Refresh> if necessary)\n
  2) open a terminal in this tab (cf terminal icon at the bottom/left)\n
  3) inside this terminal, try to run some commands to check it is working:\n
         \t cd /workspace\n
	 \t lv6 -version\n
	 \t touch toto\n
         \t ll\n
     to check if the files ownerships are correct (hopefully they are)
"

registry=gricad-registry.univ-grenoble-alpes.fr/verimag/synchrone/tools-distrib
case $1 in
    -novnc)
	docker run --detach -p 6080:80 -v "$PWD":/workspace  \
	    --env USERNAME=`id -n -u` --env USERID=`id -u` \
	    --env GROUPID=`id -g` \
	    $registry/verimag-reactive-toolbox-novnc
	echo $novnc_help
	;;
    -x11docker)
	cmd="x11docker -i $registry/verimag-reactive-toolbox-4x11docker --home=$PWD"
	echo $cmd
	$cmd || (\
	    echo "ZZZ please install x11docker: https://github.com/mviereck/x11docker"; \
	    echo "ZZZ and once it is done, do: \n\tdocker pull $registry/verimag-reactive-toolbox-4x11docker")
	;;
    *)
	unameOut="$(uname -s)"
	case "${unameOut}" in
	    Darwin*)
		# is this xhost necessary? 
		# xhost + 127.0.0.1
		DISPLAY=host.docker.internal:0
		;;
	esac
	docker run -e USERID=`id -u` -e GROUPID=`id -g` -e USER=`id -n -u`\
	    -v "$PWD":/workspace -w /workspace    \
	    -e DISPLAY=$DISPLAY \
	    -v /tmp/.X11-unix:/tmp/.X11-unix \
	    -i -t $registry/verimag-reactive-toolbox $@
esac
