#!/bin/bash
set -e
if [ -n "$DEBUG" ]; then
    set -x
fi

# The release name we are configured to run under.
typeset dmathicsserver_version='10.0.0'

# Allow customization using POSIX environment variables:
APP_DATADIR=${APP_DATADIR:-/tmp}
DOCKER=${DOCKER:-docker}
ASYMPTOTE_PDFVIEWER=${ASYMPTOTE_PDFVIWER:-/usr/bin/evince}
USER_HOME="/home/ubuntu"
MATHICS3_DJANGO_DB=${MATHICS_DJANGO_DB:-"mathics3.sqlite"}
MATHICS3_DJANGO_DB_PATH=${MATHICS_DJANGO_DB_PATH:-${USER_HOME}/.local/var/Mathics3/${MATHICS3_DJANGO_DB}}
TAG=${TAG:-latest}

MATHICS3_IMAGE=${MATHICS3_IMAGE:-mathicsorg/mathics:${TAG}}

typeset -a stripped_args
stripped_args=()

for arg in "$@" ; do
    case "$arg" in
        -h | --help | help )
			cat <<_EOH
usage:
   dmathics3server [options]

runs the Mathics3 command-line interface from a docker container.

Options specfic to dmathicsserver:

  -u | -U | --upgrade | upgrade
  pull updates to the docker container if there is a new image

  -h| --help | help
  show this help

  -V| --version
  show the dmathics3server version and exit

We will now pass help along to the docker image. Just a sec...

_EOH
			stripped_args+=("--help")
			;;
        -u | -U | --upgrade | upgrade)
			$DOCKER pull $MATHICS3_IMAGE
			;;
        -v | -V | --version)
			echo "dmathics3server version ${dmathicsserver_version}"
			exit 100
			;;
		default)
			stripped_args+=($arg)
    esac
done

# Show environment variables
for env_setting in MATHICS3_DJANGO_DB_PATH APP_DATADIR MATHICS3_IMAGE DISPLAY; do
	echo $env_setting = ${!env_setting}
done

$DOCKER run \
		-it \
		--name Mathics3-django \
		--rm \
		--env "COLORFGBG=$COLORFGBG" \
		--env="DISPLAY" \
		--env="ASYMPTOTE_PDFVIEWER=/usr/bin/evince" \
		--env "PYTHON=/opt/python3.14/bin/python3.14" \
		--user=$(id -u) \
		--workdir=/app \
		--volume="$PWD":/app \
		--volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \
		--network=host \
		$MATHICS3_IMAGE \
		--mode ui -- $stripped_args \
		# --volume="${APP_DATADIR}:/home/ubuntu/.local/var/Mathics3" \
