#!/bin/sh

# Global variables.
INSTALLATION_PREFIX="/opt/2X/Client"
CLIENT_BIN="bin/2XClient"
DBUS_BINARY="/bin/dbus-daemon"
DBUS_CMD_PARAMETERS="--fork --session --print-pid --print-address"
DBUS_PRINT_OUTPUT=""
DBUS_SESSION_ADDRESS=""
DBUS_SESSION_BINARY_PID=""
RETURN_CODE=1

print_debug()
{
  local MESSAGE="$1"

  if [ -n "${RAS_CLIENT_DEBUG}" -a -n "${MESSAGE}" ]
  then
    echo "${MESSAGE}" 1>&2
  fi
}

set_installation_prefix()
{
  local PREFIX="/opt/2X/Client"

  if [ -d "${PREFIX}" ]
  then
    INSTALLATION_PREFIX="${PREFIX}"
  else
    INSTALLATION_PREFIX="$(cd ..; pwd)"
  fi
}

#### MAIN ####

print_debug "Starting $0 script ..."
if [ -z "${DBUS_SESSION_BUS_ADDRESS}" ]
then
  print_debug "Setting installation prefix ..."
  set_installation_prefix
  print_debug "DBus session bus not detected ..."
  if [ -x "${INSTALLATION_PREFIX}/${CLIENT_BIN}" ]
  then
    print_debug "RAS Launcher binary found ..."
    if [ -x "${DBUS_BINARY}" ]
    then
      print_debug "Launching Dbus session bus ..."
      DBUS_PRINT_OUTPUT="$(${DBUS_BINARY} ${DBUS_CMD_PARAMETERS})"
      if [ -n "${DBUS_PRINT_OUTPUT}" ]
      then
        DBUS_SESSION_ADDRESS="$(echo ${DBUS_PRINT_OUTPUT} | awk '{print $1}')"
        DBUS_SESSION_BINARY_PID="$(echo ${DBUS_PRINT_OUTPUT} | awk '{print $2}')"
        if [ -n "${DBUS_SESSION_ADDRESS}" -a -n "${DBUS_SESSION_BINARY_PID}" ]
        then
          export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_ADDRESS}"
          export DBUS_SESSION_BINARY_PID
          print_debug "DBUS_SESSION_BUS_ADDRESS : ${DBUS_SESSION_BUS_ADDRESS}, DBUS_SESSION_BINARY_PID : ${DBUS_SESSION_BINARY_PID}"
        fi
      fi
    fi
  fi
fi
if [ -n "${DBUS_SESSION_BUS_ADDRESS}" ]
then
  print_debug "Starting RAS Launcher binary ..."
  ${INSTALLATION_PREFIX}/${CLIENT_BIN}; RETURN_CODE=$?
  if [ -n "${DBUS_SESSION_BINARY_PID}" ]
  then
    print_debug "Cleaning up ..."
    kill ${DBUS_SESSION_BINARY_PID}
    unset DBUS_SESSION_BINARY_PID
    unset DBUS_SESSION_ADDRESS
    unset DBUS_SESSION_BUS_ADDRESS
  fi
fi
print_debug "Exiting with return code : ${RETURN_CODE}"
exit ${RETURN_CODE}
