#!/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 "$1" -version 2>&1 | egrep -i "64-Bit" >/dev/null ; then
			echo "x86_64"
		else
			echo "x86"
		fi
	fi 
}

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

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

if [ "$GVSIG_APPLICATION_NAME" = "" ] ; then
  GVSIG_APPLICATION_NAME=gvSIG
fi
export GVSIG_APPLICATION_NAME

# gvSIG installation folder
export GVSIG_INSTALL_FOLDER="$PWD"

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

####################
# Load config file #
####################

if [ -f "$GVSIG_INSTALL_FOLDER/gvSIG.config" ] ; then
  . "$GVSIG_INSTALL_FOLDER/gvSIG.config"
fi

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

LOGGER_FILE="$GVSIG_HOME_FOLDER/${GVSIG_APPLICATION_NAME}-launcher.log"

logger () {
  # level (INFO/WARNIG) message
  local LOGGER_LEVEL="$1"
  shift
  echo "$LOGGER_LEVEL launch $@"
  if [ ! -f "$LOGGER_FILE" ] ; then
    LOGGER_TEMP1=$(dirname "$LOGGER_FILE")
    mkdir -p "$LOGGER_TEMP1"
  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"

##########################################################
# Search in gvSIG/extensiones the architecture of plugins 
# installeds and set as PREFERED_ARCHITECTURE
##########################################################

x=$(find "$GVSIG_INSTALL_FOLDER/gvSIG/extensiones" -name package.info -exec grep "architecture=[^a]" {} ';' | sort|head -n 1)
if [ "X${x}X" != "XX" ] ; then
	eval $x
	PREFERED_ARCHITECTURE="$architecture"
else
	PREFERED_ARCHITECTURE="$ARCH"
fi

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

FORCE_JAVA_32BITS=""
JAVA_HOME_OTHER_ARCHITECTURE=""

# PRIVATE JAVA HOMEs
PJH1=$(ls -dt "$GVSIG_HOME_FOLDER/jre/"*1.6* 2>/dev/null | head -1)
PJH2=$(ls -dt "$GVSIG_HOME_FOLDER/jre/"*1.5* 2>/dev/null | head -1)
PJH3=
PJH4=
PJH5=
PJH6=
if [ -d "$GVSIG_INSTALL_FOLDER/gvSIG/extensiones/jre_6_windows_i586/jre" ] ; then
PJH5="$GVSIG_INSTALL_FOLDER/gvSIG/extensiones/jre_6_windows_i586/jre"
fi
if [ -d /usr/lib/jvm ] ; then
    PJH6=$(find /usr/lib/jvm -maxdepth 1 ! -name "jvm" -name "[a-zA-Z]*" ! -type l -print)
fi

#
# 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 (optionally 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" $PJH6 ""
do
        if [ "$JAVA_HOME_TO_USE" = "" ] ; then
                continue
        fi
	logger_info "Checking JAVA_HOME ${JAVA_HOME_TO_USE}..."
        if [ ! -d "$JAVA_HOME_TO_USE" ] ; then
                logger_warn "Folder not found ($JAVA_HOME_TO_USE), skip"
                continue
        fi
        if [ ! -x "$JAVA_HOME_TO_USE/bin/java" ] ; then
                logger_warn "Not a valid JAVA_HOME ($JAVA_HOME_TO_USE), bin/java not found, skip"
                continue
        fi
	JAVA_ARCH="$(getJavaArchitecture $JAVA_HOME_TO_USE/bin/java)"
	if [ "$JAVA_ARCH" != "$PREFERED_ARCHITECTURE" ] ; then
                JAVA_HOME_OTHER_ARCHITECTURE="$JAVA_HOME_TO_USE"
                logger_warn "Prefered architecture is $PREFERED_ARCHITECTURE, java $JAVA_ARCH 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
                        JAVA_HOME="$JAVA_HOME_OTHER_ARCHITECTURE"
                        JAVA="$JAVA_HOME/bin/java"
                        logger_warn "java $PREFERED_ARCHITECTURE 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 $($WHICH java))" != "$PREFERED_ARCHITECTURE" ] ; then
                      logger_warn "java $PREFERED_ARCHITECTURE not found, using $($WHICH java)"
                fi
                unset JAVA_HOME
                JAVA="java"
        fi
else
        JAVA_HOME="$JAVA_HOME_TO_USE"
        JAVA="$JAVA_HOME/bin/java"
fi

if [ "$PREFERED_ARCHITECTURE" = "x86" ] ; then
	FORCE_JAVA_32BITS="$ARG_D32"
else 
	FORCE_JAVA_32BITS=""

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_APPLICATION_NAME 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=256M
# Maximum gvSIG memory (M=Megabytes, G=Gigabytes)
export GVSIG_MAX_MEM=1024M
# 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"

#####################
# Java debug mode ? #
#####################

DEBUG_ARGS="X${@}X"
if expr match "$DEBUG_ARGS" "X.*--pause.*X" >/dev/null; then           
    DEBUG_PAUSE="y"
else
    DEBUG_PAUSE="n"
fi

if expr match "$DEBUG_ARGS" "X.*--debug.*X" >/dev/null; then           
  DEBUG_OPTIONS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=$DEBUG_PAUSE"
else
  DEBUG_OPTIONS=""
fi

################
# 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 \
	-Xms${GVSIG_INITIAL_MEM} \
	-Xmx${GVSIG_MAX_MEM} \
	-XX:MaxPermSize=${GVSIG_MAX_PERM_SIZE} \
        $DEBUG_OPTIONS \
	-Djava.library.path=\"${GVSIG_NATIVE_LIBS}\":/usr/lib \
	-cp $GVSIG_CLASSPATH \
        $GVSIG_JAVA_PARAMS \
	$GVSIG_LAUNCHER $GVSIG_PARAMS

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