#!/bin/sh

program=`basename "$0"`

getSettings()
{
    file="${1:-/usr/local/etc/intermapperd.conf}"
    if [ -r "${file}" ] ; then
        sed -n -e 's@^[ 	]*SettingsFolder[ 	][ 	]*"\(.*\)"[ 	]*$@\1@p' \
               -e 's@^[ 	]*SettingsFolder[ 	][ 	]*\([^"].*\)$@\1@p' \
            "${file}"
    fi
}

settings=`getSettings`
directory="${settings:-/var/local/InterMapper_Settings}/Extensions"
venv="/usr/local/imdc/core/python3/venv"
pythonOptions="-OO -E"
arguments=${1+"$@"}

if [ ! -d "${venv}" ] ; then
	echo 1>&2 "${program}: cannot find virtual environment \"${venv}\""
	exit 1
elif [ ! -d "${directory}" ] ; then
	echo 1>&2 "${program}: cannot find extension directory \"${directory}\""
	exit 1
else
	cd "${directory}"
    if [ -f "switches3.zip" ] ; then
    	application="switches3.zip"
    elif [ -f "switches.zip" ] ; then
    	application="switches.zip"
    else
		echo 1>&2 "${program}: could not find \"Switches\" application archive (\"*.zip\") in directory \"${directory}\""
		exit 1
	fi
	exec sh -c ". \"${venv}/bin/activate\" ; \
		exec python ${pythonOptions} \"${application}\" ${arguments}"
fi
