#!/bin/sh

#==================================================
# This shell script is intended to be placed in
# /usr/bin/ and should be run to start a GNUmed
# client.
#
# license: GPL
# Karsten Hilbert, Sebastian Hilbert, Andreas Tille
#--------------------------------------------------

# for debugging this script
# set -x

OPTIONS=$@

# Verify the name of the script for the appendix "-debug"
# If it is symlinked to a file with this name use --debug as option
name=`basename $0`
if echo $name | grep -q -- "-debug" ; then
	name=`echo $name | sed 's/-debug//'`
	OPTIONS="$OPTIONS --debug"
fi

# The system-wide configuration file for backend profiles
#   The config file that is actually used is named like the executable
#   This enables symlinking to differently named executables and
#   starting with different options.
SYSCONF="/etc/gnumed/"`echo ${name} | sed 's/\(gnumed\)\([-_.]*\)/\1-client\2/'`".conf"
if [ ! -e ${SYSCONF} ] ; then
	echo "Global config file ${SYSCONF} missing."
	exit 1
fi

# There has to be a user config file (even if empty).
if [ ! -e ${HOME}/.gnumed/${name}.conf ] ; then
	touch ${HOME}/.gnumed/${name}.conf
fi

## Different ways to obtain the version number of the running Python interpreter
## store this here just for the purpose of education :-)
# PYVER=`python -V 2>&1 | sed 's/Python[[:space:]]\+\([0-9]\+\.[0-9]\+\).*/\1/'`
# PYVER=`pyversions -vd`
# PYVER=`python -c 'import platform; print platform.python_version()'`
PYVER=`python -c 'import sys; print sys.version[:3]'`

# this is where the gnumed.py Python script actually lives
GNUMEDDIR=/var/lib/python-support/python${PYVER}/Gnumed/wxpython

# check for explicit --conf-file option
CONFFILE=""
if echo $OPTIONS | grep -q -- "--conf-file[[:space:]]*=" ; then
	CONFFILE=`echo $OPTIONS | sed -e 's/^.*--conf-file[[:space:]]*=[[:space:]]*\([^[:space:]]\+\).*/\1/'`
	if [ ! -s ${CONFFILE} ] ; then
		echo "Given config file ${CONFFILE} missing."
		exit 1
	fi
	CONFFILE="--conf-file=${CONFFILE}"
	OPTIONS=`echo $OPTIONS | sed -e 's/--conf-file[[:space:]]*=[[:space:]]*[^[:space:]]\+//'`
fi

# source systemwide startup extension shell script if it exists
if [ -r /etc/gnumed/gnumed-startup-local.sh ] ; then
	. /etc/gnumed/gnumed-startup-local.sh
fi

# source local startup extension shell script if it exists
if [ -r ${HOME}/.gnumed/scripts/gnumed-startup-local.sh ] ; then
	. ${HOME}/.gnumed/scripts/gnumed-startup-local.sh
fi

# now run the client
python ${GNUMEDDIR}/gnumed.py ${CONFFILE} ${OPTIONS}

