##############################################################################
# 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_lcas_lcmaps_gt4
#
# DESCRIPTION : This function configures the GT4 interface for either
#               lcas and lcmaps or the Argus GSI-PEP callout
#
# AUTHORS :     Shu-Ting.Liao@cern.ch
#               Nuno.Orestes.Vaz.da.Silva@cern.ch
#               Di.Qing@cern.ch
#               David.Smith@cern.ch
#
# NOTES :       - The interface is both for GT4 gatekeeper and gridftp
#
# YAIM MODULE:  glite-yaim-core
#
##############################################################################

function find_argus_resid () {
	useargus=0
	if [ "x$USE_ARGUS" = "xyes" ]; then
		if ( echo " ${NODE_TYPE_LIST} " | egrep -q "creamCE" ); then
			resourceid=$CREAM_PEPC_RESOURCEID
		elif ( echo " ${NODE_TYPE_LIST} " | egrep -q "WMS" ); then
			resourceid=$WMS_PEPC_RESOURCEID
		else
			resourceid=$GENERAL_PEPC_RESOURCEID
		fi
		if [ "x$resourceid" != "x" ]; then
			useargus=1
		fi
	fi
}

function config_lcas_lcmaps_gt4_check () {

	requires $1 INSTALL_ROOT
	ret=$?

	if [ "x$USE_ARGUS" = "xyes" ]; then
		requires $1 ARGUS_PEPD_ENDPOINTS
		let "ret |= $?"
	fi

	find_argus_resid
	if [ $useargus -eq 0 ]; then
		requires $1 X509_VOMS_DIR X509_CERT_DIR \
			GRIDMAPFILE GRIDMAPDIR GROUPMAPFILE LCMAPS_LOG_LEVEL \
			LCMAPS_DEBUG_LEVEL LCAS_LOG_LEVEL LCAS_DEBUG_LEVEL
		let "ret |= $?"
	fi
	if [ $ret -ne 0 ]; then
		return 1
	fi
	return 0
}

function config_lcas_lcmaps_gt4_setenv () {

	find_argus_resid
	if [ $useargus -eq 0 ]; then
		yaimgridenv_set X509_VOMS_DIR "${X509_VOMS_DIR}"
		yaimgridenv_set X509_CERT_DIR "${X509_CERT_DIR}"
		yaimgridenv_set LCMAPS_LOG_LEVEL "${LCMAPS_LOG_LEVEL}"
		yaimgridenv_set LCMAPS_DEBUG_LEVEL "${LCMAPS_DEBUG_LEVEL}"
	        yaimgridenv_set LCAS_LOG_LEVEL "${LCAS_LOG_LEVEL}"
	        yaimgridenv_set LCAS_DEBUG_LEVEL "${LCAS_DEBUG_LEVEL}"
	fi
}

function config_lcas_lcmaps_gt4 () {

  ### Auxiliary script parameters
#  GLITE_LOCATION="${INSTALL_ROOT:-opt}/glite"
  GSI_AUTH="/etc/grid-security/gsi-authz.conf"
  GSI_PEP_CONFIG="/etc/grid-security/gsi-pep-callout.conf"
  GT4_INSTALL="/usr/sbin/gt4-interface-install.sh"

  ### See if we are to setup argus and if so which resouce id to use
  find_argus_resid

  ### See which arch we should do the setup for
  is64b=0
  if [ "x${OS_ARCH}" = "x64BIT" ]; then
    is64b=1
    if [ $useargus -ne 0 ]; then
      if [ -x /usr/lib/libgsi_pep_callout_gcc32dbg.so ]; then
        is64b=0
      fi
    else
      if [ -x /usr/lib/lcas/lcas_voms.mod ]; then
        is64b=0
      fi
    fi
  fi

  if [ $is64b -ne 0 ]; then
    LIBDIR="lib64"
    pepflavour=gcc64dbg
  else
    LIBDIR="lib"
    pepflavour=gcc32dbg
  fi

  ### Remove GSI_AUTH and GSI_PEP files
  ### (will recreate for lcas/lcmaps Argus as required)
  rm -f ${GSI_AUTH} ${GSI_PEP_CONFIG}

  ### Warn in case we have to skip the ARGUS configuration
  if [ "x$USE_ARGUS" = "xyes"  -a $useargus -eq 0 ]; then
	yaimlog WARNING "Configuring LCAS/LCMAPS via GSI callout, not ARGUS, as no relevant resource ID given"
  fi

  ### If Argus then write the two config files
  if [ $useargus -ne 0 ]; then

	yaimlog DEBUG "Creating GSI authorization file for Argus in ${GSI_AUTH}"

cat <<EOF> ${GSI_AUTH}
globus_mapping /usr/${LIBDIR}/libgsi_pep_callout.so argus_pep_callout 
EOF

	yaimlog DEBUG "Creating PEP configuration file for Argus in ${GSI_PEP_CONFIG}"

	if [ "x$X509_CERT_DIR" != "x" ]; then
		echo pep_ssl_server_capath ${X509_CERT_DIR} >> ${GSI_PEP_CONFIG}
	fi

	if [ "x$X509_HOST_CERT" != "x" ]; then
		echo pep_ssl_client_cert ${X509_HOST_CERT} >> ${GSI_PEP_CONFIG}
	fi

	if [ "x$X509_HOST_KEY" != "x" ]; then
		echo pep_ssl_client_key ${X509_HOST_KEY} >> ${GSI_PEP_CONFIG}
	fi

	for endpoint in $ARGUS_PEPD_ENDPOINTS; do
		echo pep_url $endpoint >> ${GSI_PEP_CONFIG}
	done

cat <<EOF>> ${GSI_PEP_CONFIG}
pep_timeout 30 # seconds
xacml_resourceid $resourceid
EOF

  else
  ### Create the GSI authorization file for lcas/lcmaps
	if test -x ${GT4_INSTALL} ; then
           yaimlog DEBUG "Creating GSI authorization file in ${GSI_AUTH}"
	   $GT4_INSTALL install
	else
           yaimlog ERROR "${GSI_AUTH} could not be created by ${GT4_INSTALL}"
	   return 1
	fi
  fi
 
  ###### LCAS config
  ###### Move aside existing configuration files
  ###### and if we're not using Argus recreate them

	### Auxiliary script parameters
	if [ "x$LCAS_DB_FILE" = "x" ]; then
	  LCAS_DB_FILE=/etc/lcas/lcas.db
	fi

	LCAS_DB_DIR=`dirname ${LCAS_DB_FILE}`

	if [ "x$BANNED_DB_FILE" = "x" ]; then
	  BANNED_DB_FILE=/etc/lcas/ban_users.db
	fi

	### Check if directory and file already exist and set suitable permissions and ownerships
	if [ -d ${LCAS_DB_DIR} ]; then
	   if [ -f ${LCAS_DB_FILE} ]; then
              yaimlog DEBUG "Backuping old LCAS_DB_FILE in ${LCAS_DB_FILE}.old"
	      mv -f ${LCAS_DB_FILE} ${LCAS_DB_FILE}.old
	   fi
	else
	   if [ $useargus -eq 0 ]; then
              yaimlog DEBUG "Creating and setting permissions in ${LCAS_DB_DIR}"
	      mkdir -p ${LCAS_DB_DIR}
	      chmod 0755 ${LCAS_DB_DIR}
	      chown root:root ${LCAS_DB_DIR}
	   fi
	fi

	if [ $useargus -eq 0 ]; then
           ### Create the lcas DB file with the content provided in this function
           yaimlog INFO "Creating LCAS_DB_FILE in ${LCAS_DB_FILE}"

cat <<EOF> ${LCAS_DB_FILE}
# LCAS database/plugin list
#
# Format of each line:
# pluginname="<name/path of plugin>", pluginargs="<arguments>"
#
pluginname=/usr/${LIBDIR}/lcas/lcas_userban.mod,pluginargs=ban_users.db
pluginname=/usr/${LIBDIR}/lcas/lcas_voms.mod,pluginargs="-vomsdir ${X509_VOMS_DIR} -certdir ${X509_CERT_DIR} -authfile ${GRIDMAPFILE} -authformat simple -use_user_dn" 
EOF

	   ### Create a banned users file if not defined
	   if [ ! -f ${BANNED_DB_FILE} ]; then
              yaimlog DEBUG "Creating an empty BANNED_DB_FILE in ${BANNED_DB_FILE}"
	      touch ${BANNED_DB_FILE}
	   fi
        else
	   if [ -f ${BANNED_DB_FILE} ]; then
	      if [ ! -s ${BANNED_DB_FILE} ]; then
		 yaimlog DEBUG "Removed an empty BANNED_DB_FILE at ${BANNED_DB_FILE}"
		 rm -f ${BANNED_DB_FILE}
	      else
		 yaimlog WARNING "A non empty BANNED_DB_FILE exists at ${BANNED_DB_FILE}, but Argus does not use it"
	      fi
	   fi
	fi
        
######

###### LCMAPS config
###### Move aside existing configuration files
###### and if we're not using Argus recreate

	### Auxiliary script parameters
	if [ "x$LCMAPS_DB_FILE" = "x" ]; then
	  LCMAPS_DB_FILE=/etc/lcmaps/lcmaps.db
	fi
	LCMAPS_DB_DIR=`dirname ${LCMAPS_DB_FILE}`

	### Check if directory and file already exist and set suitable permissions and ownerships
	if [ -d ${LCMAPS_DB_DIR} ]; then
	   if [ -f ${LCMAPS_DB_FILE} ]; then
	      yaimlog DEBUG "Backuping old LCMAPS_DB_FILE in ${LCMAPS_DB_FILE}.old"
	      mv -f ${LCMAPS_DB_FILE} ${LCMAPS_DB_FILE}.old
	   fi
	else
	   if [ $useargus -eq 0 ]; then
	      yaimlog DEBUG "Creating and setting permissions in ${LCMAPS_DB_DIR}"
	      mkdir -p ${LCMAPS_DB_DIR}
	      chmod 0755 ${LCMAPS_DB_DIR}
	      chown root:root ${LCMAPS_DB_DIR}
	   fi
	fi
	if [ $useargus -eq 0 ]; then
           ### Create the lcmaps DB file with the content provided in this function
           yaimlog INFO "Creating LCMAPS_DB_FILE in ${LCMAPS_DB_FILE}"

cat <<EOF > ${LCMAPS_DB_FILE}

# Written by Oscar Koeroo - okoeroo * at * nikhef * dot * nl
# Only for performing VOMS mappings

# where to look for modules
path = /usr/${LIBDIR}/lcmaps

# module definitions
posix_enf = "lcmaps_posix_enf.mod"
" -maxuid 1"
" -maxpgid 1"
" -maxsgid 32"

localaccount = "lcmaps_localaccount.mod"
" -gridmapfile ${GRIDMAPFILE}"

poolaccount = "lcmaps_poolaccount.mod"
" -override_inconsistency"
" -gridmapfile ${GRIDMAPFILE}"
" -gridmapdir ${GRIDMAPDIR}"

vomslocalgroup = "lcmaps_voms_localgroup.mod"
" -groupmapfile ${GROUPMAPFILE}"
" -mapmin 0"

vomslocalaccount = "lcmaps_voms_localaccount.mod"
" -gridmapfile ${GRIDMAPFILE}"
" -use_voms_gid"

vomspoolaccount = "lcmaps_voms_poolaccount.mod"
" -gridmapfile ${GRIDMAPFILE}"
" -gridmapdir ${GRIDMAPDIR}"
" -do_not_use_secondary_gids"

# gridftp related code
good = "lcmaps_dummy_good.mod"

# --only-post-verify-checks
# --allow-limited-proxy
# --max-proxy-level-ttl=<level> <time-length; example: 2d-13:37>
#   Sets a maximum lifetime for proxy certificate level <level> where <level>
#  can be 0-9 or 'l' or 'L' to indicate a Leaf proxy (last proxy # in the chain)

# policies
withvoms:
vomslocalgroup -> vomslocalaccount
vomslocalaccount -> posix_enf | vomspoolaccount
vomspoolaccount -> posix_enf

standard:
localaccount -> posix_enf | poolaccount
poolaccount -> posix_enf

EOF
######
	fi

        ### Exit with success
        return 0
}
