#!/bin/sh
# 
# ------------------------------------------------------------
# Company: Software- und Organisations-Service GmbH
# Author : Oliver Haufe <oliver.haufe@sos-berlin.com>
# Date   : 2017-08-16
# Purpose: starts installer 
# ------------------------------------------------------------


usage () {
  echo "usage: $(basename "$0") [options] [configuration-file]"
  echo "options:"
  echo "  -u | --unprivileged    | installer does not ask for root privileges"
  echo "  -E | --preserve-env    | preserves environment variables when switching to root using sudo -E"
  echo ""
  echo "configuration-file       | for silent install, use enclosed *_install.xml"
  exit 0
}

PRESERVE_ENV=""
USE_UNPRIVILEGED=""

for option in "$@"
do
	case "${option}" in
		--help|-h)      		usage
                                ;;
    	--preserve-env|-E)      PRESERVE_ENV="-E"
                                ;;
        --unprivileged|-u)      USE_UNPRIVILEGED="-Dizpack.mode=privileged"
                                ;;	
	esac
done

if [ -n "${PRESERVE_ENV}" ]; then
  shift
fi

if [ -n "${USE_UNPRIVILEGED}" ]; then
  shift
fi

if [ -n "$1" ]; then
  CHECK_PARAM_XML="$(grep "\[:choose " "$1")"
  if [ -n "${CHECK_PARAM_XML}" ]
  then
    echo "Please edit at first the file: $1"
    echo "Look to https://kb.sos-berlin.com/x/CogwAw for more information"
    exit 1
  fi
fi

JAVA="$(which java 2>/dev/null || echo "")"
test -n "${JAVA_HOME}" && test -x "${JAVA_HOME}/bin/java" && JAVA="${JAVA_HOME}/bin/java"
if [ -z "${JAVA}" ]
then
  echo "...could not identify Java environment"
  echo "...please set JAVA_HOME environment variable"
  exit 5
fi
export JAVA
export JAVA_HOME


if [ "${USER}" = "root" ]; then
  echo "${JAVA} -jar \"$(dirname "$0")/joc.2.5.12-SNAPSHOT.jar\" $*"
  "${JAVA}" -jar "$(dirname "$0")/joc.2.5.12-SNAPSHOT.jar" $*
  exit 0
fi

if [ -n "${USE_UNPRIVILEGED}" ]; then
  echo "${JAVA} ${USE_UNPRIVILEGED} -jar \"$(dirname "$0")/joc.2.5.12-SNAPSHOT.jar\" $*"
  "${JAVA}" ${USE_UNPRIVILEGED} -jar "$(dirname "$0")/joc.2.5.12-SNAPSHOT.jar" $*
  exit 0
fi

export DISPLAY
if [ -f "$HOME/.Xauthority" ]
then 
  XAUTHORITY="$HOME/.Xauthority"
  export XAUTHORITY
fi

SUDO="$(which sudo 2>/dev/null || echo "")"
if [ -n "${SUDO}" ]
then
  echo "sudo ${PRESERVE_ENV} ${JAVA} -jar \"$(dirname "$0")/joc.2.5.12-SNAPSHOT.jar\" $*"
  sudo ${PRESERVE_ENV} "${JAVA}" -jar "$(dirname "$0")/joc.2.5.12-SNAPSHOT.jar" $*
else
  echo "...couldn't find 'sudo'" 
fi
