#!/bin/bash
#
# Init file for the NorduGrid/ARC Information System
#
# based on the globus-mds v0.27 by Anders Waananen <waananen@nbi.dk>
#
# chkconfig: 2345 55 25
#
# description: ARC infosys startup script, configures and starts up
# the local ldap tree, the Index Services and the Registration Processes
#
# config: /etc/sysconfig/globus
# config: /etc/sysconfig/nordugrid
# config: /etc/arc.conf


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

function debug_echo () {
  if test $debug -gt 0; then
    echo "   $*" 1>&2
  fi
}

function do_exit () {
  conf_close
  exit $*
}


function std-header()
{
    debug_echo "Creating file: $1"
    echo '# This file was automatically generated by grid-infosys startup script. Do not modify.' > $1
    echo >> $1
}

function printregldif () {
  
  cat <<-EOF

	# Registration "$rootdn" -> "$targetsuffix"
	dn: Mds-Vo-Op-name=register, $targetsuffix
	regtype: mdsreg2
	reghn: $reghn
	regport: $regport
	regperiod: $regperiod
	type: ldap
	hn: $hn
	port: $port
	rootdn: $rootdn
	ttl: $ttl
	timeout: $timeout
	mode: cachedump
	cachettl: $cachettl
	bindmethod: $bindmethod
	EOF
}

function printldif () {

      type=$1      
      extra_args=$2

      cat <<-EOF
	# generates the nordugrid-$type info using the $ARC_CONFIG file and caches it for $cachetime seconds
	dn: $DN
	objectclass: GlobusTop
	objectclass: GlobusActiveObject
	objectclass: GlobusActiveSearch
	type: exec
	path: $NORDUGRID_LOCATION/libexec
	base: $BASE
	args: -valid-to $cachetime -config $ARC_CONFIG -dn $DN $extra_args -l $provider_loglevel
	cachetime: ${cachetime}
	timelimit: ${timelimit}
	sizelimit: ${sizelimit}

	EOF
}

function dnof () {
    
      echo "nordugrid-${1}-name=$(eval echo $(echo '$'${1}| tr '[:upper:]' '[:lower:]')_name)"
   
}

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

# source function library
if [ -r  /etc/init.d/functions ]; then
   . /etc/init.d/functions
else
  success() { echo -n "OK" 
  } 
  failure() { echo -n "FAILURE"
  }
  status() {
    pid=`pidof -o $$ -o $PPID -o %PPID -x $1`  
    if test "x$pid" != "x"; then
      echo "$1 (pid $pid) is running..."
      return 0
    fi

    if test -f "$pid_file"; then
      read pid < "$pid_file"
      if test "$pid" != ""; then
        echo "$1 stopped but pid file exists"
        return 1
      fi
    fi
    if test -f $lockfile; then
      echo "$1 stopped but lockfile exist"
      return 2
    fi
    echo "$1 is stopped"
    return 3
  }
fi


###############  Standard configuration  ######################

# sysconfig files
if [ -f /etc/sysconfig/globus ]; then
    . /etc/sysconfig/globus
fi
if [ -f /etc/sysconfig/nordugrid ]; then
    . /etc/sysconfig/nordugrid
fi

GLOBUS_LOCATION=${GLOBUS_LOCATION:-/opt/globus}
if [ ! -d "$GLOBUS_LOCATION" ]; then
  echo "GLOBUS_LOCATION not found" 
  exit 1
fi
export GLOBUS_LOCATION

NORDUGRID_LOCATION=${NORDUGRID_LOCATION:-/opt/nordugrid}
if [ ! -d "$NORDUGRID_LOCATION" ]; then
  echo "NORDUGRID_LOCATION ($NORDUGRID_LOCATION) not found" 
  exit 1
fi
export NORDUGRID_LOCATION


# source the config parsing routines
. $NORDUGRID_LOCATION/libexec/config-parser

ARC_CONFIG=${ARC_CONFIG:-/etc/arc.conf}

if [ ! -r "$ARC_CONFIG" ]; then
  echo "ARC configuration file arc.conf was not found (usually /etc/arc.conf)"
  if [ -r "/etc/nordugrid.conf" ]; then
    echo "Fallback /etc/nordugrid.conf was found, trying to use that one"
    ARC_CONFIG="/etc/nordugrid.conf"
  else
    echo "Failed to find the fallback /etc/nordugrid.conf"
    exit 1
  fi  
fi



# Overall defaults
slapd_cmd="$GLOBUS_LOCATION/libexec/slapd"
GRID_SECURITY_DIR=0		     	     
LD_LIBRARY_PATH=$GLOBUS_LOCATION/lib:$LD_LIBRARY_PATH	     
SASL_PATH=$GLOBUS_LOCATION/lib/sasl		     	     
gridmap=${GRIDMAP:-/etc/grid-security/grid-mapfile}  	     
X509_RUN_AS_SERVER=true 
registrationlog="/var/log/inforegistration.log"
slapd_loglevel="0"
provider_loglevel="1"
pid_file=""
lockfile=""
RETVAL=0
prog=grid-infosys
overwrite_config=yes
oldconfsuffix=".oldconfig"
debug=${debug:-0}
user=`id -un`
if [ -x ${GLOBUS_LOCATION}/bin/globus-hostname ]; then
  hostname=`${GLOBUS_LOCATION}/bin/globus-hostname`
else
  echo
  echo "Missing ${GLOBUS_LOCATION}/bin/globus-hostname - Is globus_common_config installed?"	      
  do_exit 1
fi
port="2135"

      
conf_init

conf_open $ARC_CONFIG


if ! conf_match infosys; then
  echo Missing infosys configuration block 2>&1
  do_exit 1
fi

conf_read common

conf_read infosys


# Set the Environment variables used by the slapd process
for v in X509_USER_CERT X509_USER_KEY GRIDMAP GRIDMAPDIR\
         GLOBUS_TCP_PORT_RANGE GLOBUS_UDP_PORT_RANGE; do
										 	 
   eval $v=\${`echo $v| tr '[A-Z]' '[a-z]'`:-\"\"}
   if [ -n "`eval echo '${'$v'}'`" ]; then
     eval export `eval echo $v`
   fi										 	 
done										 	 

								 	 										 	 
# Try (as Globus) to locate cert+key if not specified		
if   [ ! -z "${GRID_SECURITY_DIR}" ] &&
     [ -r "${GRID_SECURITY_DIR}/ldap/ldapkey.pem" ] &&	
     [ -r "${GRID_SECURITY_DIR}/ldap/ldapcert.pem" ] ; then			 	 
       X509_USER_CERT=${X509_USER_CERT:-${GRID_SECURITY_DIR}/ldap/ldapcert.pem}  	 
       X509_USER_KEY=${X509_USER_KEY:-${GRID_SECURITY_DIR}/ldap/ldapkey.pem}	 	 
elif [ -r "/etc/grid-security/ldap/ldapkey.pem" ] && 				 	 
     [ -r "/etc/grid-security/ldap/ldapcert.pem" ] ; then			 	 
       X509_USER_CERT=${X509_USER_CERT:-/etc/grid-security/ldap/ldapcert.pem}	 	 
       X509_USER_KEY=${X509_USER_KEY:-/etc/grid-security/ldap/ldapkey.pem}	 	 
       secconfdir="/etc/grid-security"						 	 
elif [ -r "${GLOBUS_LOCATION}/etc/ldap/ldapkey.pem" ] &&			 	 
     [ -r "${GLOBUS_LOCATION}/etc/ldap/ldapcert.pem" ] ; then			 	 
       secconfdir="${GLOBUS_LOCATION}/etc"					 	 
       X509_USER_CERT=${X509_USER_CERT:-${GLOBUS_LOCATION}/etc/ldap/ldapcert.pem}	 
       X509_USER_KEY=${X509_USER_KEY:-${GLOBUS_LOCATION}/etc/ldap/ldapkey.pem}	 	 
fi										 	 
        
export SASL_PATH	 	 
export LD_LIBRARY_PATH	 	 
export X509_RUN_AS_SERVER	 
export X509_USER_CERT	 	 
export X509_USER_KEY	 	 
export GRIDMAP        	 	 



if test "x$user" = "xroot" ; then
  test "x$registrationlog"  = "x" && registrationlog=/var/log/inforegistration.log
  test "x$pid_file" = "x" && pid_file=/var/run/$prog.pid
  argsfile="/var/run/grid-infosys.args"
  arc_runtime_config="/var/run/nordugrid"
  mkdir -p ${arc_runtime_config}
  # Debian does not have /var/lock/subsys
  if test -d /var/lock/subsys; then
    test "x$lockfile" = "x" && lockfile=/var/lock/subsys/$prog
  else
    test "x$lockfile" = "x" && lockfile=/var/lock/$prog
  fi    
else
  test "x$registrationlog"  = "x" && reg_logfile=/var/tmp/${user}-inforegistration.log
  test "x$pid_file" = "x" && pid_file=/var/tmp/${user}-$prog.pid
  test "x$lockfile" = "x" && lockfile=/var/tmp/${user}-$prog.lock
  argsfile="/var/tmp/${user}-grid-infosys.args"
  arc_runtime_config="/var/tmp/${user}-nordugrid"
  mkdir -p ${arc_runtime_config}
fi


# TODO for the [infosys] block:
# try to do something with the slapd log in case of none-root mode
# clean up a bit the environment variables


start()
{
        echo -n "Starting the LDAP-based Information System"
        if test $debug -gt 0 ; then
          echo 
        fi
	
   	# limits for the slapd process					       			       
	# limit_core - limits the core file size (KB)
	if test "x$user" = "xroot" ; then	
   	  if test ! "x$limit_core" = "x" ; then    					 
	    ulimit -c $limit_core	  
     	  else  				   					
     	    ulimit -c 0 			   					
   	  fi					   					 

   	  # limit_nofile - max number of open files						 
   	  if test ! "x$limit_nofile" = "x" ; then  					 
   	    ulimit -n $limit_nofile		   					   
   	  fi					   					 
	else
	  debug_echo "The startup script is run as non-root, ulimit values are not set"
	fi	
		
	debug_echo "Using GLOBUS_LOCATION: $GLOBUS_LOCATION"
	debug_echo "Using NORDUGRID_LOCATION: $NORDUGRID_LOCATION"	
	debug_echo "Using configuration file: $ARC_CONFIG"
	debug_echo "Using grid-mapfile: $GRIDMAP"			               
	debug_echo "Using ldap cert: ${X509_USER_CERT:-<no ldap certificate found>}"        
	debug_echo "Using ldap key : ${X509_USER_KEY:-<no ldap key found>}"	
      	if test ! "x$limit_core" = "x" ; then							       	 								 
      	  debug_echo "Requested/resulting max core file size : $limit_core/`ulimit -c`" 
	fi  
        if test ! "x$limit_nofile" = "x" ; then          
          debug_echo "Requested/resulting number of max open files : $limit_nofile/`ulimit -n`" 
	fi

        # overwrite_config

        if test "x$overwrite_config" = "xyes" ; then

        debug_echo "overwrite_config=yes : creating new configuration files"

        if test ! "x$oldconfsuffix" = "x"; then
          if test -r "$arc_runtime_config/grid-info-slapd.conf" ; then
            debug_echo "Making backup of $arc_runtime_config/grid-info-slapd.conf"
            cp -pf $arc_runtime_config/grid-info-slapd.conf \
                   $arc_runtime_config/grid-info-slapd.conf$oldconfsuffix
          fi
        fi

	# Creating the grid-info-slapd.conf LDAP config file
	std-header $arc_runtime_config/grid-info-slapd.conf

	(

	schemacheck="off"
	sizelimit="-1"
	threads=""
	timelimit=""
		
#
# LDAP parameters
#
        conf_read infosys
	
	test ! "x$schemacheck" 		= "x" && echo "schemacheck ${schemacheck}"
	test ! "x$sizelimit"   		= "x" && echo "sizelimit ${sizelimit}"
	test ! "x$threads"     		= "x" && echo "threads ${threads}"
	test ! "x$timelimit"   		= "x" && echo "timelimit ${timelimit}"
	test ! "x$slapd_loglevel"    	= "x" && echo "loglevel ${slapd_loglevel}"
	echo


#
# Schema files
#

	echo "#"
	echo "# Schemas"
	echo "#"
	if test -r "$GLOBUS_LOCATION/etc/openldap/schema/core.schema" ; then
		echo "include $GLOBUS_LOCATION/etc/openldap/schema/core.schema"
	else
		debug_echo "a schema file is not available"		
	fi
	if test -r "$GLOBUS_LOCATION/etc/grid-info-resource.schema"; then	
		echo "include $GLOBUS_LOCATION/etc/grid-info-resource.schema"
	else 
		debug_echo "a schema file is not available"
	fi
	if test -r "$NORDUGRID_LOCATION/share/nordugrid.schema"; then 
		echo "include $NORDUGRID_LOCATION/share/nordugrid.schema"
	else
		debug_echo "a schema file is not available"
	fi

#
# pid/args file
#

	echo
        echo "pidfile         ${pid_file}"
        echo "argsfile        ${argsfile}"
	echo
	) >> $arc_runtime_config/grid-info-slapd.conf

#
# Modulepath
#
	if test "x$globus_flavor_name" = "x" ; then
          for i in $GLOBUS_LOCATION/etc/globus_packages/globus_openldap/*_pgm*gpt; do
	    globus_flavor_name=`basename $i|sed 's@pkg_data_\(.*\)_pgm.gpt@\1@'`
	  done
        fi

	if test "x$globus_flavor_name" = "x" ; then
	  echo "Can not guess globus_flavor_name - please specify"
	  do_exit 1
	else          
            debug_echo "Using Globus flavor: $globus_flavor_name"
	fi

	modulepath="$GLOBUS_LOCATION/libexec/openldap/$globus_flavor_name"

        debug_echo "Using module path: $modulepath"
        if test -d "$modulepath"; then
          echo "modulepath      $modulepath" >> $arc_runtime_config/grid-info-slapd.conf
        else
          echo "Module path $modulepath does not exist"
          do_exit 1
        fi

#
# LDAP modules
#
        (
	  echo "moduleload      libback_ldif.la" 	      
	  echo "moduleload      libback_giis.la"  	           
        ) >> $arc_runtime_config/grid-info-slapd.conf


#
# Local Tree 
#
	if conf_match infosys; then

        # grid-info-slapd.conf

	(

          # Defaults, non-configurable values, no need to expose anything from these

	  access="access to * by * write"          
	  suffix="\"Mds-Vo-name=local, o=grid\""
	  conf="$arc_runtime_config/grid-info-resource-ldif.conf"
          anonymousbind=yes
          allowstaledata=no
	  
          # Simple support for a local ldap tree stored in GRIS-ldif backend
	    debug_echo "Enabling the Local Tree stored in the GRIS-ldif LDAP backend"  
            echo ""							      
            echo "# Standard Local Tree"				      
  	    echo "database        ldif" 				      
            echo "suffix          $suffix"				      
            echo "conf            $conf"				      
            echo "anonymousbind   $anonymousbind"			      
            echo "allowstaledata  $allowstaledata"			      
	    echo "$access"						      

        ) >> $arc_runtime_config/grid-info-slapd.conf



# detailed configuration of the Local Tree, the content of the grid-info-resource-ldif.conf
# TODO: cleanup,testing

	# grid-info-resource-ldif.conf
	(
          if test ! "x$oldconfsuffix" = "x"; then
            if test -r "$arc_runtime_config/grid-info-resource-ldif.conf" ; then
              debug_echo "Making backup of $arc_runtime_config/grid-info-resource-ldif.conf"
              cp -pf $arc_runtime_config/grid-info-resource-ldif.conf \
                     $arc_runtime_config/grid-info-resource-ldif.conf$oldconfsuffix
            fi
          fi

	  std-header $arc_runtime_config/grid-info-resource-ldif.conf

 	if conf_match cluster || conf_match se; then
	  debug_echo "Cluster or SE block found, configuring ARC infoproviders"
	fi
	
	(
	if conf_match cluster; then
	
	  conf_read common
          conf_read cluster
	  
	  # Default cluster provider limits
	  cachetime=${cachetime:-30}
	  timelimit=${timelimit:-30}
	  sizelimit=${sizelimit:-10}

	  BASE=cluster-${lrms}.pl
          cluster_name=$hostname

	  DN="$(dnof cluster),Mds-Vo-name=local,o=grid"

	  printldif cluster

	  for q in `conf_entries queue` ; do
	    
	    conf_read common
	    conf_read queue
	    conf_read queue/$q
	    
	    # Default queue-user-jobs provider limits
	    cachetime=30
	    timelimit=30
	    sizelimit=0

	    BASE=queue+jobs+users-${lrms}.pl
	    queue_name=$q

	    DN="$(dnof queue),$(dnof cluster),Mds-Vo-name=local,o=grid"

	    printldif queue "-queue $queue_name"

	  done

	fi
	
        for se in `conf_entries se` ; do
	
	  name=""
	  conf_read common
          conf_read se
          conf_read se/$se
	  if [ -z "$name" ]; then
	    name=$se
	  fi
	  
	  # Default se provider limits
	  cachetime=${cachetime:-30}
	  timelimit=${timelimit:-30}
	  sizelimit=${sizelimit:-10}

          BASE=se.pl
          DN="nordugrid-se-name=$name:$hostname,Mds-Vo-name=local,o=grid"

          printldif se "--se $se"

        done
        #TODO service provider's ldif block will come here

	) >> $arc_runtime_config/grid-info-resource-ldif.conf 
	  
	  
	# foreign providers will be enabled here, the treatment of the appropriate blocks
	# and the modification of the grid-info-resource-ldif should come here
	
        )


# Resource (cluster or SE) registrations
        # grid-info-resource-register.conf

        if test ! "x$oldconfsuffix" = "x"; then
          if test -r "$arc_runtime_config/grid-info-resource-register.conf" ; then
            debug_echo "Making backup of $arc_runtime_config/grid-info-resource-register.conf"
            cp -pf $arc_runtime_config/grid-info-resource-register.conf \
                   $arc_runtime_config/grid-info-resource-register.conf$oldconfsuffix
          fi
        fi

        std-header $arc_runtime_config/grid-info-resource-register.conf
	(
	  # Start with the Cluster registration blocks
	  for p in `conf_entries infosys/cluster/registration`; do	    	    
	
            # Local Ldap Tree registration defaults
	    targetsuffix=""
	    targethostname=""
	    targetport="" 
	    registranthostname="" 
	    registrantport=""  
	    registrantsuffix=""
	    ttl=""	
	    regperiod=120                     
            timeout=45
            cachettl=0
	    sizelimit=0            
	    bindmethod=ANONYM-ONLY
            
            conf_read infosys/cluster/registration/$p
	    
            ttl=${ttl:-$[ $regperiod * 2 ]}
	    targetsuffix=${targetsuffix:-"Mds-Vo-name=$p,o=grid"}
	    reghn=$targethostname
	    regport=${targetport:-2135}
	    hn=${registranthostname:-$hostname}
	    port=${registrantport:-$port}	      	   
	    rootdn=${registrantsuffix:-"nordugrid-cluster-name=$hn,Mds-Vo-name=local,o=grid"}
	    
	    debug_echo "Cluster Tree on $hn:$port/$rootdn REGISTERS to $reghn:$regport/$targetsuffix"            
	    printregldif

          done
	  
	  # Now  process the SE registration blocks
	  for seentry in `conf_entries infosys/se`; do	  	      	      
	    for p in `conf_entries infosys/se/$seentry/registration`; do 	      

              # Local Ldap Tree registration defaults
	      targetsuffix=""
	      targethostname=""
	      targetport="" 
	      registranthostname="" 
	      registrantport=""  
	      registrantsuffix="" 
	      ttl=""
	      regperiod=120			
              timeout=45
              cachettl=0
	      sizelimit=0 
	      bindmethod=ANONYM-ONLY
              
	      name=""
	      conf_read common
	      conf_read infosys
	      conf_read infosys/se
	      conf_read se/$seentry
	      conf_read infosys/se/$seentry
	      conf_read infosys/se/$seentry/registration
	      conf_read infosys/se/$seentry/registration/$p

	      if [ -z "$name" ]; then
		name=$seentry
	      fi
	      
              ttl=${ttl:-$[ $regperiod * 2 ]}
	      targetsuffix=${targetsuffix:-"Mds-Vo-name=$p,o=grid"}
	      reghn=$targethostname
	      regport=${targetport:-2135}
	      hn=${registranthostname:-$hostname}
	      port=${registrantport:-$port}	      
	      rootdn=${registrantsuffix:-"nordugrid-se-name=$name:$hostname,Mds-Vo-name=local,o=grid"} 
	      
	      debug_echo "$seentry SE Tree on $hostname:$port/$rootdn REGISTERS to $reghn:$regport/$targetsuffix" 
	      printregldif
	      
            done    
	  done # loop over SEs
	  
        ) >> $arc_runtime_config/grid-info-resource-register.conf

	
        fi  #end of the Local Tree


#
# Index Services: generating the config files 
#
        if conf_match infosys/index; then
		  
	  
 	  # Defaults for the Index Service slapd.conf block
	 	
	  access="access to * by * write"
	  anonymousbind=yes
          allowstaledata=no
	  conf=""
	  policyfile=""	  
	 
	  
	  for vo in `conf_entries infosys/index`; do
	  debug_echo "Enabling the Index Service $vo stored in the GIIS-ldif LDAP backend"
	  	  	  
	  (
	  
	  # grid-info-slapd.conf
	  
	  conf_read infosys/index/$vo

	  if [ -z "$name" ]; then
              echo "" 1>&2
	      echo "The Index Service must have a name, set the <name> attribute for the $vo Index Service" 1>&2
              do_exit 1
	  fi

          # Use the grid-info-site files as templates

          if test "x$conf" = "x"; then
            conf="$arc_runtime_config/grid-info-${vo}-giis.conf"
            if test ! -f "$conf"; then
              cp -p $GLOBUS_LOCATION/etc/grid-info-site-giis.conf $conf
            fi
          fi

	  echo ""
	  echo "# Index Service: $name"
	  echo "database        giis"
	  echo "suffix          \"Mds-Vo-name=$name, o=grid\""
	  echo "conf            $conf"
	  echo "policyfile      ${policyfile:-$arc_runtime_config/grid-info-${vo}-policy.conf}"
	  echo "anonymousbind   $anonymousbind"
          echo "allowstaledata  $allowstaledata"
	  if [ -r "$access" ]; then
	      cat $access
	  else
	      echo "$access"
	  fi
	  ) >> $arc_runtime_config/grid-info-slapd.conf


	  # grid-info-${vo}-policy.conf
	  
	  # Create policyfile if the user has not specified one
	  #          
	  # Allow local tree by default, override with allow=""
          allowreg="$hostname:$port"         
	   
	  if test "x$policyfile" = "x" ; then

          if test ! "x$oldconfsuffix" = "x"; then
            if test -r "$arc_runtime_config/grid-info-${vo}-policy.conf" ; then
  	      debug_echo "Making backup of $arc_runtime_config/grid-info-${vo}-policy.conf"
	      cp -pf $arc_runtime_config/grid-info-${vo}-policy.conf \
		     $arc_runtime_config/grid-info-${vo}-policy.conf$oldconfsuffix
            fi
	  fi

          # Create policy file
	  std-header $arc_runtime_config/grid-info-${vo}-policy.conf
          (
	      cat <<-EOF
		#
		#
		#  MDS registration policy file
		#
		#  example:
		#  objectclass: MdsRegistrationPolicy
		#  policydata: (&(Mds-Service-hn=dc-*.isi.edu)(Mds-Service-port=2135))
		#
		#
		
		EOF

              conf_read infosys/index/$vo

	      if test ! "x$allowreg" = "x" ; then
		echo "objectclass: MdsRegistrationPolicy"
		printf "policydata: (|"

		i=0
		tempvar=$allowreg
		while test ! -z "$tempvar" ; do

		    hn=""
		    port=""
		    suffix=""

		    hn=`echo $tempvar|cut -d: -f1 |cut -f1 -d/`

		    echo "$tempvar" | grep -q ":" && port=`echo $tempvar|cut -d: -f2|cut -d/ -f1`

		    echo "$tempvar" | grep -q "/" && suffix=`echo $tempvar|cut -d: -f2|cut -d/ -f2`
		    
		    # Force en space after comma in suffix - Globus Magic		    
		    suffix=`echo $suffix | sed 's@, *@, @g'`

		    printf "(&"
		  
		    if test ! "x$hn" = "x" ; then
			printf "(Mds-Service-hn=$hn)"
		    fi
		    
		    if test ! "x$port" = "x" ; then
		      printf "(Mds-Service-port=$port)"
		    fi

		    if test ! "x$suffix" = "x" ; then
		      printf "(Mds-Service-Ldap-suffix=$suffix)"
		    fi

		    printf ")"

		    rtmp=""
		    test ! "x$hn"     = "x" && rtmp="$rtmp$hn"
		    test ! "x$port"   = "x" && rtmp="$rtmp:$port"
		    test ! "x$suffix" = "x" && rtmp="$rtmp/$suffix"
		    debug_echo "  Allow registration to Index $vo from : $rtmp"

		    i=$[$i+1]
		    tempvar=`eval echo '$allowreg'_$i`
		done
		echo ")"
              fi

          ) >> $arc_runtime_config/grid-info-${vo}-policy.conf

	  fi  #policyfile test 


#
# Registrations of the Index Services
#
            (
	    # grid-info-resource-register.conf
	    
            for r in `conf_entries infosys/index/$vo/registration`; do

              # Index registration defaults
	      targetsuffix=""
	      targethostname=""
	      targetport="" 
	      registranthostname="" 
	      registrantport=""  
	      registrantsuffix=""
	      ttl=""
	      regperiod=120
              timeout=120
              cachettl=0
              sizelimit=0
              bindmethod=ANONYM-ONLY

              conf_read infosys/index/$vo
              conf_read infosys/index/$vo/registration/$r
              
	      ttl=$[ $regperiod * 2 ]
	      targetsuffix=${targetsuffix:-"Mds-Vo-name=$r,o=grid"}
	      reghn=$targethostname
	      regport=${targetport:-2135}
	      hn=${registranthostname:-$hostname}
	      port=${registrantport:-$port}
	      rootdn=${registrantsuffix:-"Mds-Vo-name=$vo, o=grid"}	     
	      
              if [ -n "$targetsuffix" -a -n "$targethostname" ]; then
                printregldif
                debug_echo "Index Service $hn:$port/$rootdn REGISTERS to $reghn:$regport/$targetsuffix"
              fi

            done
            ) >> $arc_runtime_config/grid-info-resource-register.conf


          done
	  
	fi # conf_match infosys/index

        fi # overwrite_config


#
# Finished with the config file generation.
# Time to start the whole Infosys through grid-info-soft-register
#
		
        CMD="$GLOBUS_LOCATION/sbin/grid_info_daemon - $GLOBUS_LOCATION/sbin/grid-info-soft-register -log $registrationlog -f $arc_runtime_config/grid-info-resource-register.conf  -- "

        if [ -z "$slapd_hostnamebind" ]; then
          slapd_hostnamebind=$hostname
        fi
	
#       Use the raw slapd rather than grid-info-slapd since we setup the environment ourselves
#       slapd_cmd="$GLOBUS_LOCATION/libexec/slapd"
#       don't try to remove -d $debug! otherwise you lose the registrations
        CMD="$CMD $slapd_cmd -h ldap://$slapd_hostnamebind:$port -f $arc_runtime_config/grid-info-slapd.conf -d $slapd_loglevel -u $user"
  			        
        debug_echo "Executing: $CMD &"        


# 	This could be better done
	if test "`id -un`" = "$user" ; then
  	   debug_echo "Starting services as user: $user"
	   $CMD &
  	else
	   debug_echo "Changing to user: $user before starting services"
#	   sudo -u $user $CMD &
           su $user -p -c "$CMD &"
	fi	
		

	RETVAL=$?

	[ "$RETVAL" = 0 ] && success

	[ "$RETVAL" = 0 ] && touch $lockfile

	echo
}

stop()
{
        echo -n "Stopping the LDAP-based Information System "

        if [ -f $pid_file ] ; then
          kill `cat $pid_file` && success "$prog shutdown" || failure "$prog shutdown"
          rm -f $pid_file $lockfile $argsfile
        else
          failure "$prog shutdown"
        fi

	echo
}

case "$1" in
  	start)
		start
		;;
	stop)
		stop
		;;
	restart|reload)
		stop
		start
		;;
	condrestart)
		if [ -f $lockfile ] ; then
			stop
			# avoid race
			sleep 3
			start
		fi
		;;
	status)
		status $slapd_cmd		
		RETVAL=$?		
		;;
	*)
		echo "Usage: $0 {start|stop|restart|reload|condrestart|status}"
		RETVAL=1
                ;;
esac

do_exit $RETVAL
