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

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

# Allow customization using POSIX environment variables:
APP_DATADIR=${APP_DATADIR:-/tmp}
DOCKER=${DOCKER:-docker}
TAG=${TAG:-latest}

XAUTH=${XAUTH:-$HOME/.Xauthority}
touch $XAUTH

DEVICE=''
if [[ -r /dev/dri ]]; then
    DEVICE='--device=/dev/dri:/dev/dri'
fi

CONFIGDIR=${CONFIGDIR:-$HOME/.config/mathicsscript/}


# TODO: allow setting:
#	MATHICSSCRIPT_HISTSIZE \

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

typeset -a stripped_args
stripped_args=()

for arg in "$@" ; do
    case "$arg" in
        -h | --help | help )
			cat <<_EOH
Usage: mathicsscript [OPTIONS] [FILE]

  A command-line interface to Mathics run in a docker container

Options specfic to dmathicsscript:

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

  -h| --help | help
  Show this help.

  --dversion
  Show the dmathicsscript version and exit.

Useful Environment Variables:

APP_DATADIR: where application data should be saved. The default is: ${APP_DATADIR}
DOCKER: the name of the docker program to run. The default is: ${DOCKER}
CONFIGDIR: directory where Mathics command history is saved. The default is: ${CONFIGDIR}
MATHICS_IMAGE: Mathics image to use. The default is: ${MATHICS_IMAGE}
TAG: tag used in MATHICS_IMAGE above. The default is: ${TAG}
XAUTH: .Xauthority file. The default is: ${XAUTH}

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

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

cd $(dirname ${BASH_SOURCE[0]})
source ./term-background.sh

[[ -x ./term-background.sh ]] && source ./term-background.sh

if [[ $COLORFGBG == '15;0' ]] ; then
    # Dark background
    style="--style inkpot"

else
    # Light background
    style="--style colorful"
fi

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

$DOCKER run \
	--rm \
	--env "DISPLAY=$DISPLAY" \
	--name mathics-cli \
	--tty \
	--interactive \
	--network=host \
	--volume="$PWD":/app \
	--volume "${APP_DATADIR}:/usr/src/app/data" \
	--volume "${CONFIGDIR}:/usr/src/app/.config/mathicsscript" \
	$DEVICE \
    $MATHICS_IMAGE \
	--mode cli -- $style $stripped_args
