##############################################################################
# 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 :        yaim
#
# DESCRIPTION : This is YAIM main function. To learn more about YAIM, visit:
#               https://twiki.cern.ch/twiki/bin/view/EGEE/YAIM
#
# MAINTAINERS : yaim-contact@cern.ch
#
# NOTES :
#
# YAIM MODULE:  glite-yaim-core
#
##############################################################################


function configure_node () {


####################################
# Checking only required variables #
# not running the configuration    #
####################################

mycheck="no"
myexplain="no"
if [ "x$1" = "xcheck" ]; then
 shift;
 mycheck="yes"
fi
if [ "x$1" = "xexplain" ]; then
 shift;
 myexplain="yes"
fi

#########################
# Configuration targets #
#########################
# SORT: we're not dependent on command line order

NODE_TYPE_LIST=""
for i in `echo $@ | tr ' ' '\n' `; do
  if ( echo $i | grep -q "-" ); then
    prefix=${i%-*}
    if [ "x${prefix}" != "xlcg" ] && [ "x${prefix}" != "xglite" ] && [ "x${prefix}" != "xegee" ] && [ "x${prefix}" != "xemi" ] && [ "x${prefix}" != "x" ]; then
      yestr ${YEX_CONFTARGET}
      yaimlog ERROR "${YERRORSTR}"
      exit ${YEX_CONFTARGET}
    fi
    node=`echo ${i} | sed -e 's/^lcg-//' -e 's/^glite-//' -e 's/^egee-//' -e 's/^emi-//'`
  else
    node=${i}
  fi
  #if [ "x${i}" == "xglite-CE" ]; then i="gliteCE"; fi -> This is not needed since the glite-CE is not supported.
  NODE_TYPE_LIST="${NODE_TYPE_LIST} $node"
done

# Removing trailing and leading spaces from the node type list

mylist=`echo ${NODE_TYPE_LIST} | awk '{print $_}'`
export NODE_TYPE_LIST=${mylist}

yaimlog DEBUG "Resulted NODE_TYPE_LIST is : ${NODE_TYPE_LIST}"

####################
# Environment file #
####################
# Not sourced with 'explain' and 'check' options

if [ "x${myexplain}" = "xno" ] && [ "x${mycheck}" = "xno" ]; then

  yaimgridenv_set GRID_ENV_LOCATION "${GRID_ENV_LOCATION}"
#  yaimgridenv_set EDG_LOCATION ${INSTALL_ROOT}/edg
#  yaimgridenv_set LCG_LOCATION ${INSTALL_ROOT}/lcg 
#  yaimgridenv_set GLITE_LOCATION ${INSTALL_ROOT}/glite
  yaimgridenv_set LCG_LOCATION /usr               
if ( echo "${NODE_TYPE_LIST}" | egrep -qi 'TAR' ); then
  yaimgridenv_set GLITE_LOCATION ${INSTALL_ROOT}/usr
else
  yaimgridenv_set GLITE_LOCATION /usr
fi
  yaimgridenv_set GLITE_LOCATION_VAR ${GLITE_LOCATION_VAR}



  # LD_LIBRARY_PATHs
  # not needed for EMI
#  if [ "x${OS_ARCH}" = "x64BIT" ]; then
#   if [ -d ${LCG_LOCATION}/lib64 ]; then
#    yaimgridpath_prepend LD_LIBRARY_PATH ${LCG_LOCATION}/lib64
#   fi
#   if [ -d ${LCG_LOCATION}/lib ]; then
#    yaimgridpath_prepend LD_LIBRARY_PATH ${LCG_LOCATION}/lib
#   fi
#   if [ -d ${GLITE_LOCATION}/lib64 ]; then
#    yaimgridpath_prepend LD_LIBRARY_PATH ${GLITE_LOCATION}/lib64
#   fi
#   if [ -d ${GLITE_LOCATION}/lib ]; then
#    yaimgridpath_prepend LD_LIBRARY_PATH ${GLITE_LOCATION}/lib
#   fi
#  else
#   yaimgridpath_prepend LD_LIBRARY_PATH ${LCG_LOCATION}/lib 
#   yaimgridpath_prepend LD_LIBRARY_PATH ${GLITE_LOCATION}/lib
#  fi
  # PATH 
  # not needed for EMI
#  yaimgridpath_prepend PATH ${LCG_LOCATION}/bin
  yaimgridpath_prepend PATH ${EDG_LOCATION}/bin
#  yaimgridpath_prepend PATH ${GLITE_LOCATION}/bin
  
  # MANPATH
  # not needed for EMI
#  yaimgridpath_prepend MANPATH ${GLITE_LOCATION}/share/man
#  yaimgridpath_prepend MANPATH ${LCG_LOCATION}/man
#  yaimgridpath_prepend MANPATH ${LCG_LOCATION}/share/man
#  yaimgridpath_prepend MANPATH ${EDG_LOCATION}/share/man
# temporary for YAIM
  yaimgridpath_prepend MANPATH ${YAIM_ROOT}/glite/share/man
fi


#################
# VO management #
#################
vo_param_init ${config_dir}


#################
# Function list #
#################
# Source node-info.d for all configured services

for node in ${NODE_TYPE_LIST} ; do

    unset nodeinfosuffix
    if [ "x30" = "x${GLITE_VERSION}" ] ; then
       nodeinfosuffix="_30"
    fi

    # This is now removed due to bug #45103
    # unset GLITE_EXTERNAL_ROOT
    # if ( echo ${node} | egrep -q 'TAR' ) ; then
    #   export GLITE_EXTERNAL_ROOT="${INSTALL_ROOT}/external"
    # fi    

    # Build the node-info.d file name to be sourced
    if ( echo ${node} | egrep -q 'gliteCE' ) ; then
      if [ -f "${mythisdir}/../node-info.d/glite-ce$nodeinfosuffix" ] ; then
        node_info_file=${mythisdir}/../node-info.d/glite-ce$nodeinfosuffix
      else
        node_info_file=${mythisdir}/../node-info.d/glite-ce
      fi
    else
      if ( echo ${node} | egrep -q 'creamCE' ) ; then
        if [ -f "${mythisdir}/../node-info.d/glite-creamce$nodeinfosuffix" ] ; then
          node_info_file=${mythisdir}/../node-info.d/glite-creamce$nodeinfosuffix
        else
          node_info_file=${mythisdir}/../node-info.d/glite-creamce
        fi
      else
        if ( echo ${node} | egrep -q 'MPI_CE' ) ; then
          if [ -f "${mythisdir}/../node-info.d/glite-mpi_ce$nodeinfosuffix" ] ; then
            node_info_file=${mythisdir}/../node-info.d/glite-mpi_ce$nodeinfosuffix
          else
            node_info_file=${mythisdir}/../node-info.d/glite-mpi_ce
          fi
        else 
          if ( echo ${node} | egrep -q 'CE' ) ; then
            if [ -f "${mythisdir}/../node-info.d/lcg-ce$nodeinfosuffix" ] ; then
              node_info_file=${mythisdir}/../node-info.d/lcg-ce$nodeinfosuffix
            else
              node_info_file=${mythisdir}/../node-info.d/lcg-ce
            fi
          else
           if [ -f "${mythisdir}/../node-info.d/emi-`echo $node | tr '[:upper:]' '[:lower:]'`" ] ; then
             node_info_file=${mythisdir}/../node-info.d/emi-`echo $node | tr '[:upper:]' '[:lower:]'`
           else
            if [ -f "${mythisdir}/../node-info.d/glite-`echo $node | tr '[:upper:]' '[:lower:]'`$nodeinfosuffix" ] ; then
              node_info_file=${mythisdir}/../node-info.d/glite-`echo $node | tr '[:upper:]' '[:lower:]'`$nodeinfosuffix
            else
              if [ -f "${mythisdir}/../node-info.d/glite-`echo $node | tr '[:upper:]' '[:lower:]'`" ] ; then 
                node_info_file=${mythisdir}/../node-info.d/glite-`echo $node | tr '[:upper:]' '[:lower:]'`
              else
                if [ -f "${mythisdir}/../node-info.d/egee-`echo $node | tr '[:upper:]' '[:lower:]'`" ] ; then
                  node_info_file=${mythisdir}/../node-info.d/egee-`echo $node | tr '[:upper:]' '[:lower:]'`
                else # No glite, lcg or egee prefix  
                  node_info_file=${mythisdir}/../node-info.d/`echo $node | tr '[:upper:]' '[:lower:]'`
                fi # egee config targets
              fi # glite config targets
            fi # glite config targets 3.0
           fi # emi config targets
          fi # lcg CE config target
        fi # MPI_CE config target
      fi # cream CE config target
    fi # glite CE config target

    # Source node-info.d/${node}
    if [ -f "$node_info_file" ]; then
      yaimlog DEBUG "Sourcing node definition file: $node_info_file"
    	source $node_info_file
    else
        eval ${node}_FUNCTIONS='"'$(
            if [ -f "${mythisdir}/../defaults/node-info.def" ] ; then
                source ${mythisdir}/../defaults/node-info.def
                eval echo '$'`echo ${node}_FUNCTIONS`
            fi
            )'"'
        yaimlog DEBUG "Sourcing node definition file: ${mythisdir}/../defaults/node-info.def"
    fi

    if [ "x`eval echo '$'${node}_FUNCTIONS`" = "x" ]; then
	    yaimlog ERROR "The node-info for service ${node} not found in ${mythisdir}/../node-info.d"
      yaimlog ERROR "nor in ${mythisdir}/../defaults/node-info.def"
    	exit 1
    else
    	functions="${functions} "`eval echo '$'${node}_FUNCTIONS`
    fi
done


##############
# Duplicates #
##############
# Remove dupes from the list while maintaining order
# (if the arr entry doesn't exist yet, a[$0]++ returns 0)
# Put config_bdii_only at the end in the function list to make sure the necessary config files
# provided by different node types are correctly build before startung uo the bdii

if ( echo ${functions} | grep config_bdii_only >> /dev/null); then
  functions="`echo $functions | tr ' ' '\n' | awk 'a[$0]++ == 0' | awk '{ if ($0=="config_bdii_only") print ""; else print $0 }' | grep -v "^$"` config_bdii_only"
else
  functions=`echo $functions | tr ' ' '\n' | awk 'a[$0]++ == 0'`
fi


#########
# Check #
#########
# Executing the functions if mycheck is yes it means that we are just checking
# the defined variables but do not configuring, so even if a check function fails
# we have to continue.

myresult=0;


if [ "x${myexplain}" = "xyes" ]; then
   yaimlog INFO "Explaining what the functions are doing:"
   for FUNCTION in $functions; do
     yaimlog INFO "Function ${FUNCTION} does:"
     functiontoprint="${FUNCTIONS_DIR}/${FUNCTION}"
     if [ -f "${FUNCTIONS_DIR}/local/${FUNCTION}" ]; then
        functiontoprint="${FUNCTIONS_DIR}/local/${FUNCTION}"
     fi
     cat ${functiontoprint} | grep "####@" | sed 's/####@/    #/g'
   done
   exit 0;
fi

for FUNCTION in $functions; do
   run check ${FUNCTION}_check 
   myret=$?
   if [ ${myret} -eq 1 ] && [ "x${mycheck}" = "xno" ]; then
       yaimlog ERROR "Error during running check functions."
       yaimlog ERROR "Please define your missing variables ! Exiting."
       exit 1;
   fi
   if [ ${myret} -eq 1 ] && [ "x${mycheck}" = "xyes" ]; then
       myresult=1;
   fi
done

if [ "x${mycheck}" = "xyes" ]; then 
    yaimlog INFO "Checking is done."
    if [ ${myresult} -eq 1 ]; then
       yaimlog ERROR "Undefined variables have been found. Please define them in your site-info.def"
       exit 1;
    else
       yaimlog INFO "All the necessary variables to configure ${NODE_TYPE_LIST} are defined in your configuration files."
       yaimlog INFO "Please, bear in mind that YAIM only guarantees the definition of variables"
       yaimlog INFO "controlled in the _check functions."
    fi
  
else

    for FUNCTION in $functions; do
      run check ${FUNCTION}_setenv 
      run ${FUNCTION}
      myret=$?
      if [ ${myret} -ne 0 ]; then
       echo_failure;
       yaimlog ERROR "Error during the configuration.Exiting."; 
       exit 1;
      fi
    done
    echo_success;
    yaimlog INFO "Configuration Complete."
fi

vo_param_close

exit 0

}
