#!/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; }

vnc_help="\n
This docker image is based on webtop\n
cf https://docs.linuxserver.io/images/docker-webtop/\n
\n
How to use this docker image\n
============================\n
  1) open a tab in your browser at\n
      \n
         \t http://localhost:3000/\n
 \t or\n
         \t https://localhost:3001/\n
     \n
     (<Refresh> the browser if necessary)\n
  2) open a terminal in this tab (cf terminal icon at the bottom)\n
  3) inside this terminal, try to run some commands to check it is working:\n
         \t cd /workspace\n
         \t pwd\n
	 \t lv6 -version\n
	 \t touch toto\n
     and\n
         \t ls -l\n
     to check if files ownerships are correct (hopefully they are)
"

registry=gricad-registry.univ-grenoble-alpes.fr/verimag/synchrone/tools-distrib
case $1 in
    -vnc)
	docker run  \
	    --name=dockver \
	    -e TITLE=dockver \
	    -e FM_HOME="/workspace/" \
	    -p 3000:3000 \
	    -p 3001:3001 \
	    -e USERNAME=`id -n -u` \
	    -e PUID=`id -u` \
	    -e PGID=`id -g` \
#    -e TZ=Etc/UTC \
#    -e SUBFOLDER=/ `#optional` \
#    --security-opt seccomp=unconfined `#optional` \
#      -v /path/to/data:/config \
#      -v /var/run/docker.sock:/var/run/docker.sock `#optional` \
#    --device /dev/dri:/dev/dri `#optional` \
#    --shm-size="1gb" `#optional` \
#    --restart unless-stopped \
	    -v $PWD:/workspace verimag-reactive-toolbox-kasmvnc

    echo $vnc_help
	;;
# use the (obselete) novnc based image
    -novnc)
	docker run --detach -p 6080:80 -v "$PWD":/workspace  \
	    --env USERNAME=`id -n -u` --env USERID=`id -u` \
	    --env GROUPID=`id -g` \
	    jahierwan/verimag-reactive-toolbox-novnc
	;;
    -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
