#!/bin/sh

#==================================================
# This shell script is intended to be placed in
# /usr/bin/ and should be run to start a GNUmed
# client.
#
# $Source: /sources/gnumed/gnumed/gnumed/dists/Linux/gnumed,v $
# $Id: gnumed,v 1.4 2005/07/11 16:55:27 ncq Exp $
# license: GPL
# Karsten Hilbert, Sebastian Hilbert, Andreas Tille
#--------------------------------------------------

# 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 config file taht is actually used is named like the executable
# This enables symlinking to differently named executables and starting
# with different options.
CONFSOURCE=/etc/gnumed/${name}.conf

## 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]'`

GNUMEDDIR=/var/lib/python-support/python${PYVER}/Gnumed/wxpython
# set -x

# check for explicite conffile option
# in this case we forget the name magic from above
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
    fi
    CONFFILE="--conf-file=${CONFFILE}"
    OPTIONS=`echo $OPTIONS | sed -e 's/--conf-file[[:space:]]*=[[:space:]]*[^[:space:]]\+//'`
else
    # copy global config file to user directory because /etc/gnumed is not writable
    if [ ! -s ${HOME}/.gnumed/${name}.conf ] ; then
        if [ ! -e ${CONFSOURCE} ] ; then
	    echo "Global config file ${CONFSOURCE} missing."
	    exit
	fi
	if [ ! -d ${HOME}/.gnumed ] ; then
	    mkdir -p ${HOME}/.gnumed
	fi
        cp -a ${CONFSOURCE} ${HOME}/.gnumed/${name}.conf
    fi
    CONFFILE="--conf-file=${HOME}/.gnumed/${name}.conf"
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/gnumed-startup-local.sh ] ; then
    . ${HOME}/.gnumed/gnumed-startup-local.sh
fi

python ${GNUMEDDIR}/gnumed.py ${CONFFILE} ${OPTIONS}
