#!/bin/sh
#
# gvSIG. Desktop Geographic Information System.
#
# Copyright (C) 2007-2013 gvSIG Association.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA  02110-1301, USA.
#
# For any additional information, do not hesitate to contact us
# at info AT gvsig.com, or visit our website www.gvsig.com.
#

# gvSIG.sh

set -e
#set -x

####################
# Identify OS and Architecture  #
####################

UNAME=$(uname -a)
if echo "$UNAME" | grep -i "win" >/dev/null; then
	OS="win"
	ARG_D32=""
        CPSEP=";"
else 
	if echo "$UNAME" | grep -i "lin" >/dev/null ; then
		OS="lin"
		# Only linux support -d32 arg
		ARG_D32="-d32"
                CPSEP=":"
	else
		OS="unknown"
		ARG_D32=""
                CPSEP=":"
	fi
fi
if echo "$UNAME" | egrep -i "(x86_64)|(amd64)" >/dev/null ; then
	ARCH="x86_64"
else
	ARCH="x86"
fi

########################

getJavaArchitecture() {
	if [ "$ARCH" = "x86" ] ; then
                # Si la arquitectura del SO es x86 decimos 
                # que la de java es x86
		echo "x86"
	else
                # si la arquitectura es x86_64, comprobamos
                # la arquitectura de la java que nos pasan
		if [ "$OS" = "win" ] ; then
			if "$1" -version 2>&1 | egrep -i "64-Bit" >/dev/null ; then
				echo "x86_64"
			else
				echo "x86"
			fi
		else 
			if ! "$1" -d32 -version 2>/dev/null ; then
				echo "x86_64"
			else
				echo "x86"
			fi
		fi
	fi 
}

#################################
# Set install and home folders  #
#################################

# Go into the gvSIG installation folder, just in case
cd "$(dirname $0)"

# gvSIG installation folder
export GVSIG_INSTALL_FOLDER="$PWD"

# gvSIG home folder
export GVSIG_HOME_FOLDER="$HOME/gvSIG"

#################
# Logger config #
#################

LOGGER_FILE="$GVSIG_HOME_FOLDER/gvSIG.log"

logger () {
  # level (INFO/WARNIG) message
  local LOGGER_LEVEL="$1"
  shift
  echo "$LOGGER_LEVEL launch $@"
  if [ ! -f "$LOGGER_FILE" ] ; then
    mkdir -p "$(dirname $LOGGER_FILE)"
  fi
  echo "$LOGGER_LEVEL launch $@" >> "$LOGGER_FILE"
}

logger_info () {
  logger "INFO" "$@"
}

logger_warn () {
  logger "WARNING" "$@"
}

#########################
# Locate whitch command #
#########################

if type which >/dev/null; then
        WHICH=which
else
        WHICH=type
fi

logger_info "gvSIG Installation folder: $GVSIG_INSTALL_FOLDER"
logger_info "gvSIG home folder: $GVSIG_HOME_FOLDER"

###########################################
# Variables depending on the installation #
###########################################

FORCE_JAVA_32BITS=""
JAVA_HOME_OTHER_ARCHITECTURE=""

# PRIVATE JAVA HOMEs
PJH1=$(ls -d "$GVSIG_HOME_FOLDER/jre/"*1.6* | head -1)
PJH2=$(ls -d "$GVSIG_HOME_FOLDER/jre/"*1.5* | head -1)
PJH3="$GVSIG_INSTALL_FOLDER/gvSIG/extensiones/jre_6_windows_i586/jre"
PJH4=
PJH5=

#
# in next line, JAVA_HOME is set during instalation process
DEFAULT_JAVA_HOME="${JAVA_HOME}"
#
#
# Try to use java from:
# 1. Java specified in JAVA_HOME variable
# 2. Java specified in the instalation process
# 3. Java in the HOME/gvsig/jre folder (optionallinfoy created during installation process)
# 4. Java in the system path.
#
export JAVA_HOME
export JAVA
export FORCE_JAVA_32BITS

for JAVA_HOME_TO_USE in "$JAVA_HOME" "$DEFAULT_JAVA_HOME" "$PJH1" "$PJH2" "$PJH3" "$PJH4" "$PJH5"  ""
do
        if [ "$JAVA_HOME_TO_USE" = "" ] ; then
                continue
        fi
        if [ ! -d "$JAVA_HOME_TO_USE" ] ; then
                logger_warn "Incorrect JAVA_HOME ($JAVA_HOME_TO_USE), skip"
                continue
        fi
        if [ ! -x "$JAVA_HOME_TO_USE/bin/java" ] ; then
                logger_warn "Incorrect JAVA_HOME ($JAVA_HOME_TO_USE), bin/java not found, skip"
                continue
        fi
	if [ "$(getJavaArchitecture $JAVA_HOME_TO_USE/bin/java)" = "x86_64" ] ; then
                JAVA_HOME_OTHER_ARCHITECTURE="$JAVA_HOME_TO_USE"
                logger_warn "java 32 bits not found in $JAVA_HOME_TO_USE, skip"
                continue
        fi
        break
done

if [ "$JAVA_HOME_TO_USE" = "" ] ; then
        # Try to use the java in the system path
        if ! type java >/dev/null ; then
                # java not found in the system path
                if [ "$JAVA_HOME_OTHER_ARCHITECTURE" != "" ] ; then
                        FORCE_JAVA_32BITS=""
                        JAVA_HOME="$JAVA_HOME_OTHER_ARCHITECTURE"
                        JAVA="$JAVA_HOME/bin/java"
                        logger_warn "java 32 bits not found in the system path, using $JAVA_HOME_OTHER_ARCHITECTURE"
                else
                        logger_warn "java not found in the system"
                        exit 1
                fi
        else
		if [ "$(getJavaArchitecture)" = "x86_64" ] ; then
                      FORCE_JAVA_32BITS=""
                      logger_warn "java 32 bits not found, using $($WHICH java)"
      		else
			FORCE_JAVA_32BITS="$ARG_D32"
                fi
                unset JAVA_HOME
                JAVA="java"
        fi
else
        JAVA_HOME="$JAVA_HOME_TO_USE"
        JAVA="$JAVA_HOME/bin/java"
        FORCE_JAVA_32BITS="$ARG_D32"
fi
logger_info "Using java " $($WHICH "$JAVA")

###################################################################
# Variables not depending (at least directly) on the installation #
###################################################################

# gvSIG native libraries location 
export GVSIG_NATIVE_LIBS=${GVSIG_INSTALL_FOLDER}/native:${HOME}/.depman/lib

# Native libraries path
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$GVSIG_NATIVE_LIBS"

export LIBRARIES=""
# Load gvSIG Andami jars and dependencies for the classpath 
for i in ./lib/*.jar ; do
  if [ "$i" != "./lib/*.jar" -a "$i" != "" ]; then
	LIBRARIES="${LIBRARIES}${CPSEP}${i}"
  fi 
done
for i in ./lib/*.zip ; do
  if [ "$i" != "./lib/*.zip" -a "$i" != "" ]; then
	LIBRARIES="${LIBRARIES}${CPSEP}${i}"
  fi 
done

# echo Initial libraries found: ${LIBRARIES}

# gvSIG Andami launcher
if [ "$GVSIG_LAUNCHER" = "" ] ; then
  GVSIG_LAUNCHER=org.gvsig.andamiupdater.Updater
fi
if [ "$GVSIG_PARAMS" = "" ] ; then
  GVSIG_PARAMS="gvSIG gvSIG/extensiones $@"
fi

export GVSIG_LAUNCHER
export GVSIG_PARAMS

# gvSIG initial classpath
export GVSIG_CLASSPATH="$LIBRARIES:$GVSIG_CLASSPATH"

########################
# Memory configuration #
########################

# Initial gvSIG memory (M=Megabytes, G=Gigabytes)
export GVSIG_INITIAL_MEM=128M
# Maximum gvSIG memory (M=Megabytes, G=Gigabytes)
export GVSIG_MAX_MEM=512M
# Maximum permanent memory size: needed to load classes and statics
export GVSIG_MAX_PERM_SIZE=96M


#############################
# Plugin specific variables #
#############################

### ecw provider
export NCS_USER_PREFS="$HOME/.erm/ncsuserprefs.xml"

### gdal provider
# GDAL data files
export GDAL_DATA="${GVSIG_INSTALL_FOLDER}/data/gdal"

#############################
# Execute plugin's autorun  #
#############################

for PLUGIN_FOLDER in "$GVSIG_INSTALL_FOLDER/gvSIG/extensiones/"* 
do
  if [ -f "$PLUGIN_FOLDER/autorun.sh" ] ; then
    logger_info "Running autorun from plugin $(basename $PLUGIN_FOLDER)"
    . "$PLUGIN_FOLDER/autorun.sh"
  fi
done

logger_info "LD_LIBRARY_PATH=$LD_LIBRARY_PATH"

################
# Launch gvSIG #
################

# For Java parameters documentation and more parameters look at:
# http://download.oracle.com/javase/6/docs/technotes/tools/windows/java.html
# http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html

logger_info Launching gvSIG: ${JAVA} \
	$FORCE_JAVA_32BITS \
	-Djava.library.path=/usr/lib:"${GVSIG_NATIVE_LIBS}" \
	-cp $GVSIG_CLASSPATH \
	-Xms${GVSIG_INITIAL_MEM} \
	-Xmx${GVSIG_MAX_MEM} \
	-XX:MaxPermSize=${GVSIG_MAX_PERM_SIZE} \
	$GVSIG_LAUNCHER $GVSIG_PARAMS


"${JAVA}" 	-cp "$GVSIG_CLASSPATH" $GVSIG_LAUNCHER $GVSIG_PARAMS
