#!/bin/sh
#
# License: MIT (see LICENSE.txt)
# THIS PROGRAM COMES WITH NO WARRANTY
#
# Copyright 2011-2016 Carsten Grohmann
#
# Shell script to start wxGlade
#
# The wxGlade main script is called wxglade.py. It will be searched at
# three places:
#  1. parallel to this script
#  2. in the module directory of the current Python
#  3. in a parallel Python module directory

# Keep this up to date with version.py and sphinx/conf.py
WXG_VERSION="1.1.1"

CURR_DIR=$(dirname "$0")

# search order for Python interpreter
INTERPRETER_LIST="${CURR_DIR}/python python3 python2 \
                  python2.7 python27 \
                  python"

# Use the binary from PYTHON_BIN, if this environment variable is set
if [ "$PYTHON_BIN" ]; then
  INTERPRETER_LIST="$PYTHON_BIN"
fi

for INTERPRETER in $INTERPRETER_LIST; do
  ${INTERPRETER} -V >/dev/null 2>&1
  if [ $? -ne 0 ]; then
    continue
  fi

  # Python interpreter found
  PYTHON_BIN=$INTERPRETER

  # determined current python version
  PY_VERSION=$(${PYTHON_BIN} -c 'import sys; print("%d.%d"%(sys.version_info.major, sys.version_info.minor))')

  EGG_DIR="wxGlade-${WXG_VERSION}-py${PY_VERSION}.egg"

  # determined prefix of the Python module directory structure
  if [ -d "/usr/lib/pymodules/python${PY_VERSION}/wxglade" ]; then
    WXG_MODULE_PATH="/usr/lib/pymodules/python${PY_VERSION}/wxglade"
  elif [ -d "/usr/lib/pymodules/python${PY_VERSION}/site-packages/${EGG_DIR}/wxglade" ]; then
    WXG_MODULE_PATH="/usr/lib/pymodules/python${PY_VERSION}/site-packages/${EGG_DIR}/wxglade"
  else
    WXG_MODULE_PATH="/usr/lib/python${PY_VERSION}/wxglade"
  fi

  # search wxglade.py
  # dist-packages is only used in Debian and Debian derivates
  for DIR in \
     "${CURR_DIR}" \
     "${WXG_MODULE_PATH}" \
     "${CURR_DIR}/../lib/python${PY_VERSION}/site-packages/wxglade" \
     "${CURR_DIR}/../lib/python${PY_VERSION}/site-packages/${EGG_DIR}/wxglade" \
     "${CURR_DIR}/../lib/python${PY_VERSION}/dist-packages/wxglade" \
     ; do
    BINARY="${DIR}/wxglade.py"
    if [ -e "${BINARY}" ]; then
      WXG_BINARY="$BINARY"
      break
    fi
  done
  if [ -n "${WXG_BINARY}" ]; then
    break
  fi
done

if [ ! "$PYTHON_BIN" ]; then
  echo "ERROR: No interpreter for Python found!"
  echo "       Please install Python to run wxGlade!"
  exit 1
fi

if [ ! "${WXG_BINARY}" ]; then
  echo "ERROR: wxglade.py not found!"
  exit 1
fi

# exec wxGlade
exec "${PYTHON_BIN}" "${WXG_BINARY}" "$@"
