#!/bin/bash
#centos7 version

#set -x
#edited for the tarball by Matt 28/2/2014
#updated 28/3/2014
#updated some more 1/4/2014
#updated even more 9/4/2014
#28/9/2016 centos 7 version

#In order to run in a fully relocatable fashion the env variables
#JAVA_HOME and X509_VOMSES or VOMS_USERCONF need to be set

#Needs a version of openjdk over other java implimentations. 
#JAVA_HOME should point to openjdk

#This option allows admins to have a seperate JAVA_HOME like variable for 
#the voms tools if they have several JAVA implimentations.
#Thanks Asoka for this

if [ ! -z $EMI_OVERRIDE_JAVA_HOME ]; then
export JAVA_HOME=$EMI_OVERRIDE_JAVA_HOME
fi


if [ "x$VOMSCLIENTS_LIBS" == "x" ]; then

  PRG="$0"
  while [ -h "$PRG" ]; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
      PRG="$link"
    else
      PRG=`dirname "$PRG"`/"$link"
    fi
  done

  PRGDIR=`dirname "$PRG"`

  VOMSCLIENTS_HOME=`cd "$PRGDIR/../.." ; pwd`

  VOMSCLIENTS_LIBS=$VOMSCLIENTS_HOME/usr/share/java/voms-clients-java/
fi

# ':' separated list of jars, for the classpath
#VOMSCLIENTS_CP=`ls -1 $VOMSCLIENTS_LIBS/*.jar | tr '\n' ':'`

#In the CentOS7 voms clients the jar files  are in difference places to the SL6 version, hence the horror below to build the classpath
VOMSCLIENTS_CP=`ls -1 $VOMSCLIENTS_HOME/usr/share/java/*.jar | tr '\n' ':'``ls -1 $VOMSCLIENTS_HOME/usr/share/java/canl-java/*.jar | tr '\n' ':'``ls -1 $VOMSCLIENTS_HOME/usr/share/java/voms-api-java/*.jar | tr '\n' ':'``ls -1 $VOMSCLIENTS_HOME/usr/share/java/voms-clients-java/*.jar | tr '\n' ':'`


# the class implementing voms-proxy-init
VOMSPROXYINIT_CLASS="org.italiangrid.voms.clients.VomsProxyInit"

# JVM options
VOMS_CLIENTS_JAVA_OPTIONS=${VOMS_CLIENTS_JAVA_OPTIONS:-"-Xmx16m"}

#be a little more dynamic in finding java
which java >/dev/null 2>&1
check_java=$?

if test -n "${JAVA_HOME}" ;
then
java_to_use=$JAVA_HOME/bin/java;
elif [ $check_java = 0 ]
then
java_to_use=java
else
echo "Warning: java not found in path and JAVA_HOME not set." 
fi

#check if user has explicitly set the vomses directory to use
#single or double dashed options are allowable. 
isvomsesset=0
vomsesvar="--vomses"
vomsesvar2="-vomses"
for var in "$@"; do
if [ "$var" == "$vomsesvar" ] || [ "$var" == "$vomsesvar2" ]; then 
isvomsesset=1;
fi; 
done

#check to see if x509_vomses or voms_userconf set - favour the 
#x509_vomses variable if both
if test -n "${X509_VOMSES}" ; then
vomsestouse=$X509_VOMSES;
elif test -n "${VOMS_USERCONF}"; then
vomsestouse=$VOMS_USERCONF;
fi

#if vomses isn't set and $VOMS_USERCONF exists add in vomses
if  [ $isvomsesset = 0 ] &&  test -n "${vomsestouse}" ; then
set -- "$@" "--vomses" "$vomsestouse"; 
fi

$java_to_use $VOMS_CLIENTS_JAVA_OPTIONS -cp $VOMSCLIENTS_CP $VOMSPROXYINIT_CLASS "$@"
