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

set -x

usage="dockver [option]\n
where option can be:\n
   -h,-help,--help \tthis message\n
   -pull, --pull, \n
   -update, --update \tupdate the docker images\n
   -kasm,--kasm,-vnc, --vnc \tuse the webtop/kasmVNC image (the display is done via a browser)\n
"

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
    -h|-help|--help)
	echo $usage
	;;
    -pull|--pull|-update|--update)
	docker pull  $registry/verimag-reactive-toolbox
	docker pull  $registry/verimag-reactive-toolbox-kasmvnc
	;;
    -kasm|--kasm|-vnc|--vnc)
	shift
	docker stop /dockver || echo "dockver was not running"
	docker rm /dockver || echo "dockver was not running"
	docker run $@ \
	    --name=dockver \
	    --security-opt seccomp=unconfined \
	    -e TITLE=dockver \
	    -p 3000:3000 \
	    -p 3001:3001 \
	    -e CUSTOM_USER=verimag \
	    -e USERNAME=`id -n -u` \
	    -e PUID=`id -u` \
	    -e PGID=`id -g` \
	    -v $PWD:/config/workspace $registry/verimag-reactive-toolbox-kasmvnc
#    -e TZ=Etc/UTC \
#    -e SUBFOLDER=/ `#optional` \
#      -v /var/run/docker.sock:/var/run/docker.sock `#optional` \
#    --device /dev/dri:/dev/dri `#optional` \
#    --shm-size="1gb" `#optional` \
#    --restart unless-stopped \

    echo $vnc_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
