##############################################################################
# Copyright (c) Members of the EGEE Collaboration. 2004. 
# See http://www.eu-egee.org/partners/ for details on the copyright 
# holders.  
#
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
#
#    http://www.apache.org/licenses/LICENSE-2.0 
#
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS 
# OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License.
##############################################################################
#
# NAME :        config_glite_ui
#
# DESCRIPTION : This function configures the 3.1 UI. 
#
# AUTHORS :     Elena.Puncheva@cern.ch
#               Preslav.Konstantinov@cern.ch
#               Robert Harakaly <robert.harakaly@cern.ch>
#
# NOTES : 
#
# YAIM MODULE:  glite-yaim-clients
#                 
##############################################################################

function config_glite_ui_check () {
  requires $1 PX_HOST VOS
  if [ $? -eq 1 ]; then   
    exit 1   
  fi 

  if [ "x${UIWMS_SERVICE_DISCOVERY}" == "xno" ]; then
    requires $1 WMS_HOST
    if [ $? -eq 1 ]; then
      exit 1
    fi
  fi

 return 0

}

function config_glite_ui_setenv () {
# not needed for EMI
#  if [ -d ${GLITE_EXTERNAL_ROOT:-}/opt/SOAPpy/lib/python2.3/site-packages ]; then
#    yaimgridpath_append PYTHONPATH ${GLITE_EXTERNAL_ROOT:-}/opt/SOAPpy/lib/python2.3/site-packages 
#  fi
#  if [ -d ${GLITE_EXTERNAL_ROOT:-}/opt/fpconst/lib/python2.4/site-packages ]; then
#    yaimgridpath_append PYTHONPATH ${GLITE_EXTERNAL_ROOT:-}/opt/fpconst/lib/python2.4/site-packages
#  fi 
#  if [ -d ${GLITE_EXTERNAL_ROOT:-}/opt/fpconst/lib/python2.3/site-packages ]; then
#    yaimgridpath_append PYTHONPATH ${GLITE_EXTERNAL_ROOT:-}/opt/fpconst/lib/python2.3/site-packages
#  fi
#  if [ -d ${GLITE_EXTERNAL_ROOT:-}/opt/ZSI/lib/python2.4/site-packages ]; then
#    yaimgridpath_append PYTHONPATH ${GLITE_EXTERNAL_ROOT:-}/opt/ZSI/lib/python2.4/site-packages
#  fi
#  if [ -d ${GLITE_EXTERNAL_ROOT:-}/opt/ZSI/lib/python2.3/site-packages ]; then
#    yaimgridpath_append PYTHONPATH ${GLITE_EXTERNAL_ROOT:-}/opt/ZSI/lib/python2.3/site-packages 
#  fi
#  if [ -d ${INSTALL_ROOT}/log4cpp/lib ]; then
#    yaimgridpath_append LD_LIBRARY_PATH ${INSTALL_ROOT}/log4cpp/lib  
#  fi
#  if [ -d ${INSTALL_ROOT}/classads/lib64/ ]; then  
#    yaimgridpath_append LD_LIBRARY_PATH         ${INSTALL_ROOT}/classads/lib64/    
#  fi
  yaimgridenv_set GLITE_SD_PLUGIN ${GLITE_SD_PLUGIN}
  yaimgridenv_set GLITE_SD_SERVICES_XML ${GLITE_SD_SERVICES_XML}
#  yaimgridenv_set GLITE_WMS_LOCATION ${INSTALL_ROOT}/glite
  if ( ! echo $NODE_TYPE_LIST | egrep -q VOBOX ) ; then
      yaimgridenv_setind X509_USER_PROXY "/tmp/x509up_u\$(id -u)"
  fi

  return 0
}

function config_glite_ui(){

  ####@ Find out if Service Discovery should be enabled or not
  yaimlog DEBUG "Find out if Service Discovery should be enabled or not"
  # Note: If UIWMS_SERVICE_DISCOVERY is defined, the assigned value is not affected
  # by the fact of WMS_HOST being or not defined. 
  if [ "x${UIWMS_SERVICE_DISCOVERY}" == "x" ]; then
    if [ "x${WMS_HOST}" == "x" ]; then
       UIWMS_SERVICE_DISCOVERY="yes"
    else
       UIWMS_SERVICE_DISCOVERY="no"
    fi
  fi

  mkdir -p /tmp/glite/glite-ui
  chmod a+wt /tmp/glite/glite-ui
 
#  GLITE_LOCATION=${INSTALL_ROOT}/glite
  
  # Set defaults for OUTPUT_STORAGE, INSTALL_ROOT and DEFAULT_VO
	if [ $UID -eq 0 ]; then
    	OUTPUT_STORAGE=${OUTPUT_STORAGE:-/tmp/jobOutput}
  	else
    	OUTPUT_STORAGE=${OUTPUT_STORAGE:-${HOME}/jobOutput}
  	fi
  	INSTALL_ROOT=${INSTALL_ROOT:-/opt}
  	DEFAULT_VO=${DEFAULT_VO:-unspecified}

#not needed in EMI  
  	# ------------------------------------------------------------
  	# Configure WMS Python UI
  	# ------------------------------------------------------------
	####################################
	#   UI python command line specific configuration file
	####################################

	ClassAdsHelper_file=ClassAdsHelper.conf
	cat > $ClassAdsHelper_file << EOF
ClassAdsHelper:file=/etc/glite_wmsui_cmd_var.conf
requirements = other.GlueCEStateStatus == "Production"
rank = - other.GlueCEStateEstimatedResponseTime
RetryCount = 3 
ErrorStorage= "/tmp"
OutputStorage="$OUTPUT_STORAGE"
ListenerStorage = "/tmp"
LoggingTimeout = 30
LoggingSyncTimeout = 30
NSLoggerLevel = 0
DefaultStatusLevel = 1
DefaultLogInfoLevel = 1
DefaultVo = "$DEFAULT_VO"
EOF
	python $FUNCTIONS_DIR/../libexec/ClassAdsHelper.py
	rm -f $ClassAdsHelper_file

  	# ------------------------------------------------------------
  	# Make sure $OUTPUT_STORAGE directory exists and has correct mode
  	# ------------------------------------------------------------
  	[ -d "$OUTPUT_STORAGE" ] || mkdir -p "$OUTPUT_STORAGE"
  	chmod 1777 "$OUTPUT_STORAGE"
  
  	# ------------------------------------------------------------
  	# Configure VO specific WMS UI parameters
  	# ------------------------------------------------------------
  	for vo in $VOS; do
    	vodir=$(echo "$vo" | tr "[:upper:]" "[:lower:]")
#different path in EMI
#    	mkdir -p "$GLITE_LOCATION/etc/$vodir"
        mkdir -p "/etc/glite-wms/$vodir"
    
    	# Use per VO WMS host and proxy, if set. Otherwise use global default
    	if [ -z "`get_vo_param ${vo} WMS_HOSTS`" ] ; then
        	VO_WMS_HOSTS=$WMS_HOST
    	else
        	VO_WMS_HOSTS=`get_vo_param ${vo} WMS_HOSTS`
    	fi

        if [ -z "`get_vo_param ${vo} LB_HOSTS`" ] ; then
                VO_LB_HOSTS=$LB_HOST
        else
                VO_LB_HOSTS=`get_vo_param ${vo} LB_HOSTS`
        fi


    	if [ x`get_vo_param ${vo} PX_HOST` = 'x' ] ; then
        	VO_PX_HOST=$PX_HOST
    	else
        	VO_PX_HOST=`get_vo_param ${vo} PX_HOST`
    	fi

first=0
for i in ${VO_LB_HOSTS}; do
if [ $first -eq 0 ]; then
  LBS="{\"$i\"}"
  first=1
else
  LBS="${LBS}, {\"$i\"}"
fi
done

first=0
for i in ${VO_WMS_HOSTS}; do
if [ $first -eq 0 ]; then
  WMPROXY_END_POINTS="\"https://$i:7443/glite_wms_wmproxy_server\""
  first=1
else
  WMPROXY_END_POINTS="${WMPROXY_END_POINTS}, \"https://$i:7443/glite_wms_wmproxy_server\""
fi
done

# different paths in EMI
    	# ------------------------------------------------------------
    	# Configure WMS UI Client
    	# ------------------------------------------------------------
    	cat > $ClassAdsHelper_file << EOF
ClassAdsHelper:file=/etc/glite-wms/$vodir/glite_wmsui.conf
VirtualOrganisation = "$vo"
HLRLocation = ""
LBAddresses = {$LBS}
MyProxyServer = "$VO_PX_HOST"
WMProxyEndpoints = {$WMPROXY_END_POINTS}
ListenerStorage = "/tmp"
ErrorStorage = "/tmp"
OutputStorage = "$OUTPUT_STORAGE"
JdlDefaultAttributes/SignificantAttributes = {"Requirements", "Rank", "FuzzyRank"}
JdlDefaultAttributes/requirements = other.GlueCEStateStatus == "Production"
JdlDefaultAttributes/MyProxyServer = "$VO_PX_HOST"
JdlDefaultAttributes/ShallowRetryCount = 10
JdlDefaultAttributes/AllowZippedISB = true
JdlDefaultAttributes/PerusalFileEnable = false
JdlDefaultAttributes/rank =- other.GlueCEStateEstimatedResponseTime
JdlDefaultAttributes/RetryCount = 3
EOF
        python $FUNCTIONS_DIR/../libexec/ClassAdsHelper.py
       	rm -f $ClassAdsHelper_file

    	# ------------------------------------------------------------
    	# Configure WMS Proxy
    	# ------------------------------------------------------------
    	cat << EOF > $ClassAdsHelper_file
ClassAdsHelper:file=/etc/glite-wms/$vodir/glite_wms.conf
virtualorganisation = "$vo"
WMProxyEndpoints = {$WMPROXY_END_POINTS}
ListenerStorage = "/tmp"
ErrorStorage = "/tmp"
OutputStorage = "$OUTPUT_STORAGE"
JdlDefaultAttributes/SignificantAttributes = {"Requirements", "Rank", "FuzzyRank"} 
JdlDefaultAttributes/requirements = other.GlueCEStateStatus == "Production"
JdlDefaultAttributes/MyProxyServer = "$VO_PX_HOST"
JdlDefaultAttributes/ShallowRetryCount = 10
JdlDefaultAttributes/AllowZippedISB = true
JdlDefaultAttributes/PerusalFileEnable = false
JdlDefaultAttributes/rank =- other.GlueCEStateEstimatedResponseTime
JdlDefaultAttributes/RetryCount = 3
EOF

if [ "x${UIWMS_SERVICE_DISCOVERY}" == "xyes" ]; then
  ####@ Enable Service Discovery
  yaimlog DEBUG "Enable Service Discovery"
  cat << EOF >> $ClassAdsHelper_file
EnableServiceDiscovery = true
LBServiceDiscoveryType = "org.glite.lb.server"
WMProxyServiceDiscoveryType = "org.glite.wms.wmproxy"
EOF
fi
        python $FUNCTIONS_DIR/../libexec/ClassAdsHelper.py
        rm -f $ClassAdsHelper_file

  	done # for each vo

# no VDT in EMI
  # This is needed by VDT 1.10.1
#  if [ -f ${GLOBUS_LOCATION}/setup/globus/setup-openssl ]; then
#    yaimlog DEBUG "Running setup script to configure openssl for VDT" 
    # remove any openssl symbolic link which might already exist in the globus bindir, otherwise if
    # setup-openssl finds this before the system openssl it will recreate the link but pointing to itself
#    if [ -h ${GLOBUS_LOCATION}/bin/openssl ]; then
#      rm ${GLOBUS_LOCATION}/bin/openssl
#    fi
    # Fix to pass GPT_LOCATION and GLOBUS_LOCATION to setup-openssl 
#    GPT_LOCATION=${GPT_LOCATION} GLOBUS_LOCATION=${GLOBUS_LOCATION} ${GLOBUS_LOCATION}/setup/globus/setup-openssl 2>&1
#    if [ $? -ne 0 ]; then
#      yaimlog WARNING "${GLOBUS_LOCATION}/setup/globus/setup-openssl didn't finish succesfully"
#      yaimlog WARNING "Clients using openssl may not work properly, please have a look !"
#    fi 
#  fi

#temporary fix for glite-wms-ui-configuration
rm -f /etc/profile.d/glite-wmsui*

return 0

}
