##############################################################################
# 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_vomsmap
# 
# DESCRIPTION : This function creates the necessary configuration files as
#               well as the static VOMS gridmapfile and groupmapfile for
#               3.1 nodes. It's extracted from old config_mkgridmap.
#
# AUTHORS :     Shu-Ting.Liao@cern.ch
#               Nuno.Orestes.Vaz.da.Silva@cern.ch
#               Di.Qing@cern.ch
#
# NOTES :       - Initially this function was created for 3.1 LCG CE, but it may 
#                 be extended to other new 3.1 node types as well.
#
# YAIM MODULE:  glite-yaim-core
#                 
##############################################################################

function config_vomsmap_check () {
 	requires $1 INSTALL_ROOT USERS_CONF GROUPS_CONF VOS \
          		GRIDMAPFILE GRIDMAPDIR GROUPMAPFILE DN_GRIDMAPFILE VOMS_GRIDMAPFILE CONFIG_GRIDMAPDIR
  return $?
}


function config_vomsmap_setenv () {

	yaimgridenv_set GRIDMAPDIR "${GRIDMAPDIR}"

}


function config_vomsmap () {

  ####@ Check whether USERS_CONF exists
  if [ ! -e ${USERS_CONF} ]; then
    yaimlog ERROR "USERS_CONF ${USERS_CONF} not found"
    yestr ${YEX_NOSUCHFILE}
    yaimlog ERROR "${YERRORSTR}"
    exit ${YEX_NOSUCHFILE}
  fi

  ####@ Check whether GROUPS_CONF exists
  if [ ! -e ${GROUPS_CONF} ]; then
    yaimlog ERROR "GROUPS_CONF ${GROUPS_CONF} not found"
    yestr ${YEX_NOSUCHFILE}
    yaimlog ERROR "${YERRORSTR}"
    exit ${YEX_NOSUCHFILE}
  fi

  ####@ Check the format of users in USERS_CONF
  check_users_conf_format

  ####@ Create the grid-map directory
  if [ "x${CONFIG_GRIDMAPDIR}" == "xyes" ]; then
    yaimlog INFO "Creating grid-map directory in ${GRIDMAPDIR}"
    mkdir -p ${GRIDMAPDIR}
    if ( echo "$NODE_TYPE_LIST" | egrep -q "WMS" ); then 
      chown root:${GLITE_GROUP} ${GRIDMAPDIR}
    else 
      chown root:${EDG_GROUP} ${GRIDMAPDIR}
    fi 
    chmod 770 ${GRIDMAPDIR}
  fi

  #####@ Delete the old gridmapfile and groupmapfile
  rm -f ${VOMS_GRIDMAPFILE} ${GROUPMAPFILE}

  ####@ Create the new ones
  yaimlog INFO "Creating voms grid-map file in ${VOMS_GRIDMAPFILE}"
  yaimlog INFO "Creating voms groupmap file in ${GROUPMAPFILE}"

  ####@ Create the VOMS grid-map and groupmap file.
  for VO in `echo $VOS | tr '[:lower:]' '[:upper:]'`; do
    yaimlog DEBUG "**** VO ${VO} ****"
    ####@ Set some variables
    VO_lower=`echo $VO | tr '[:upper:]' '[:lower:]'`
    vo_group=`users_getvogroup $VO`
    vo_user_prefix=`users_getvoprefix $VO`
    [ -z "$vo_user_prefix" ] && vo_user_prefix=$VO_lower
    vo_pool_account=.$vo_user_prefix


    if [ "x${CONFIG_GRIDMAPDIR}" == "xyes" ]; then
      ####@ gridmapdir files
      yaimlog DEBUG "create gridmapdir files"
      for user in `awk -F: '$5 == "'$VO_lower'" && $2 ~ /[0-9]$/ {print $2}' $USERS_CONF`; do
        f=${GRIDMAPDIR}/${user}
	[ -f $f ] || touch $f
      done
    else
      yaimlog INFO "No gridmapdir files are created since CONFIG_GRIDMAPDIR=no"
    fi

    ####@ Create special accounts
    vo_match="/$VO_lower"
    vo_tags=`awk -F: '$4!="" && $1~"^\"(/VO=[^/]*/GROUP=)?" vo_match "[/\"]" && seen[$4]++ == 0 { print $4 }
                     ' vo_match=$vo_match $GROUPS_CONF`
    for special in $vo_tags; do
 		  eval ${special}users='`users_getspecialusers $VO $special`'
   	  eval ${special}group=`users_getspecialgroup $VO $special`
		  eval ${special}prefix=`users_getspecialprefix $VO $special`
		  eval u=\$${special}users
  		case $u in
		    ?*' '?*) use_pool_accounts=true;;
		    *) if grep -q ":${u%% *}:.*," $USERS_CONF; then
			       case $u in
      			   *[0-9]) yaimlog WARNING "Only 1 pool account defined for tag '$special' of VO $VO"
            			     use_pool_accounts=true;;
			        *) # static account defined with multiple groups
			           use_pool_accounts=false
			       esac
	         else
			       use_pool_accounts=false
	    	   fi
		  esac

		  case $SPECIAL_POOL_ACCOUNTS in
		    [1TtYy]*) use_pool_accounts=true;;
  		  [0FfNn]*)	use_pool_accounts=false;;
		    ?*)	yaimlog WARNING "SPECIAL_POOL_ACCOUNTS has bad value '$SPECIAL_POOL_ACCOUNTS'"
		  esac

 		  if $use_pool_accounts && ! grep -q ":${u%% *}:.*," $USERS_CONF; then
	      yaimlog ERROR "Pool accounts for tag '$special' of VO $VO need multiple groups"
		  fi

  		if ! $use_pool_accounts; then
        eval ${special}_pool_account="\${${special}users%% *}"
	    else
  	    eval ${special}_pool_account=.\$${special}prefix
    	fi
   		eval u=\$${special}_pool_account
   		test "${u:-.}" = . &&
	    yaimlog ERROR "Could not determine mapping for tag '$special' of VO $VO"

    done # special accounts

 	  ####@ VOMS gridmapfile and groupmapfile
	  #
	  # example groups.conf entries:
	  #
	  # "/cms/ROLE=lcgadmin":::sgm:
	  # "/cms/ROLE=production":::prd:
	  # "/cms/HeavyIons":cms01:1340::
	  # "/cms/Higgs":cms02:1341::
	  # "/cms/StandardModel":cms03:1342::
	  # "/cms/Susy":cms04:1343::
	  # "/cms/*"::::
	  # "/cms"::::
	  #

	  map_wildcards=`get_vo_param ${VO} MAP_WILDCARDS`
 	  sed -n '
      s|^"/VO=[^/]*/GROUP=|"|
      s|^"'"$vo_match"'[/"]|&|p
      s|^"'"$vo_match"'[/"].*:'"$VO_lower"':* *$|&|p
  	  ' $GROUPS_CONF | uniq | while read line; do
		    fqan_glite=`echo "$line" | sed 's/\(".*"\).*/\1/;s/role/Role/i'`
  	    case $fqan_glite in
	        */Role=*)	Role=	;;
		      *)Role=/Role=NULL
		    esac

 		    extra=$Role/Capability=NULL
		    line=` echo "$line" | sed 's/.*"://'  `
	      group=`echo "$line" | sed 's/:.*//'   `
	      line=` echo "$line" | sed 's/[^:]*://'`
	      gid=`  echo "$line" | sed 's/:.*//'   `
	      line=` echo "$line" | sed 's/[^:]*://'`
	      flag=` echo "$line" | sed 's/:.*//'   `

 	      if [ "$flag" ]; then
          eval u=\$${flag}_pool_account
    	    eval g=\$${flag}group
	      elif [ "$group" ]; then
	        if [ "x$CONFIG_USERS" = "xyes" ]; then
	          groupadd ${gid:+"-g"} ${gid:+"$gid"} "$group" 2>&1 | grep -v exists
	        else
	          yaimlog WARNING "User configuration is disabled. Group $group won't be added" 
	        fi
	        u=$vo_pool_account
	        g=$group
	      else
          u=$vo_pool_account
          g=$vo_group
	      fi

	      # provide "grep" with some input...
	      echo mapping "$fqan_glite"
   		  # skip if empty (should not happen)
	      if [ -z "$u" -o -z "$g" ]; then
          yaimlog WARNING "No mapping found for $fqan_glite in $GROUPS_CONF" 
    	    continue
	      fi

	      if [ "x$map_wildcards" = "xyes" ]; then
	        case $fqan_glite in
		        */Role=*|*/\*\") # nothing needed for roles or explicit wildcards
                             ;;
		        *) # add wildcards for subgroups and roles
		           # (LCMAPS will require roles to be explicitly matched)
		           echo "${fqan_glite%\"}/*/Role=*\" $u" >> ${VOMS_GRIDMAPFILE}
		           echo "${fqan_glite%\"}/*/Role=*\" $g" >> ${GROUPMAPFILE}
		           echo "${fqan_glite%\"}/*\" $u" >> ${VOMS_GRIDMAPFILE}
		           echo "${fqan_glite%\"}/*\" $g" >> ${GROUPMAPFILE}
	        esac
	      fi

	      ####@ Old format
	      echo "${fqan_glite%\"}$extra\" $u" >> ${VOMS_GRIDMAPFILE}
	      echo "${fqan_glite%\"}$extra\" $g" >> ${GROUPMAPFILE}
	      ####@ New format
	      echo "$fqan_glite $u" >> ${VOMS_GRIDMAPFILE}
	      echo "$fqan_glite $g" >> ${GROUPMAPFILE}

    done | grep . > /dev/null || yaimlog WARNING "VO '$VO' not found in $GROUPS_CONF"

    ####@ clean for next VO
    for special in $vo_tags; do
      eval ${special}_pool_account=
      eval ${special}group=
    done

	done # End of VO loop

# temporary here the definition of INSTALL_ROOT
INSTALL_ROOT=/usr

	####@ Install a cron job for checking gridmap
  cron_job lcg-expiregridmapdir root  "5 * * * * \
	${INSTALL_ROOT}/sbin/lcg-expiregridmapdir.pl -e 240 -v >> /var/log/lcg-expiregridmapdir.log 2>&1"

unset INSTALL_ROOT

  ####@ Concatenate this file to the "general" grid-mapfile
  if ( echo " ${NODE_TYPE_LIST} " | egrep -q "CE|SCAS|storm" ) && ( ! echo " ${NODE_TYPE_LIST} " | egrep -q "creamCE|CLUSTER" ); then
    if [ ! -f ${DN_GRIDMAPFILE} ]; then
      yaimlog WARNING "${DN_GRIDMAPFILE} not defined for DN mapping!"
    fi
    yaimlog DEBUG "Adding voms grid-mapfile to ${GRIDMAPFILE}"
    tmp_gmf=${GRIDMAPFILE}.tmp
    f=/var/log/lcg-ce-mkgridmap.log
    if ( echo " ${NODE_TYPE_LIST} " | egrep -q "SCAS" ); then
      f=/var/log/scas-mkgridmap.log
    fi
    cmd="cp ${DN_GRIDMAPFILE} $tmp_gmf; cat ${VOMS_GRIDMAPFILE} >> $tmp_gmf; mv $tmp_gmf ${GRIDMAPFILE}"
    eval $cmd
    yaimlog DEBUG "Adding the extension of the grid-map file in the cronjob definition"
    cron_job lcg-ce-mkgridmap root "0 * * * * (date; $cmd) >> $f 2>&1"
  else
    yaimlog INFO "Copying the ${VOMS_GRIDMAPFILE} in the standard location ${GRIDMAPFILE}"
    cp ${VOMS_GRIDMAPFILE} ${GRIDMAPFILE}
  fi

  ### Exit with success
  return 0
}

