##############################################################################
# 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_gip_glue2_storm
#
# DESCRIPTION : This function configures the published information on a StoRM SE.
#
# AUTHORS :     grid-release@infn.it
#
# NOTES :
#
# YAIM MODULE:  yaim-storm
#
##############################################################################

# Get from config_gip_dpm in glite-yaim-dpm-4.0.6-1 and modified for StoRM
function l_write_vo_info () {

  tofile=$1
  # get_owner
  echo -n "get_owner =" >> ${tofile}
  nvo=0
  for VO in ${VOS}; do
    echo -n " echo ${VO};" >> ${tofile}
    nvo=1
  done
  if [ ${nvo} -eq 0 ]; then
    echo " echo" >> ${tofile}
  else
    echo >> ${tofile}
  fi
  # get_acbr
  echo -n "get_acbr =" >> ${tofile}
  nvo=0
  for VO in ${VOS}; do
    echo -n " echo VO:${VO};" >> ${tofile}
    nvo=1
  done
  if [ $nvo -eq 0 ]; then
    echo " echo" >> ${tofile}
  else
    echo >> ${tofile}
  fi

  return 0

}

#
# Size
#
function get_size () {

  FUNC="get_size"

  if [ "$#" -ne "9" ]; then
    yaimlog ERROR "${FUNC}: Internal Error!"
    yaimlog ERROR "Please set: Verify the number of parameters passed to the ${FUNCTION} function"
    yestr ${YEX_SOFTWARE}
    yaimlog ERROR "${YERRORSTR}"
    return ${YEX_SOFTWARE}
  fi

  SIZE=`/usr/bin/curl -s http://$2:$3/info/status/$1`
  if [ -z "${SIZE}" ]; then
    # convert in byte (base 10)
    yaimlog DEBUG "${FUNC}: the command /usr/bin/curl -s http://$2:$3/info/status/$1 return no value; check StoRM Backend service status."
    yaimlog DEBUG "${FUNC}: set a temporary value."
    total=$(($4*(1000*1000*1000)))
    used=0
    free=$(($4*(1000*1000*1000)))
    reserved=0
    available=$(($4*(1000*1000*1000)))
  elif [ "${SIZE}" == "<html><body><h1>Internal Error</h1></body></html>" ]; then
    # convert in byte (base 10)
    yaimlog DEBUG "${FUNC}: the command /usr/bin/curl -s http://$2:$3/info/status/$1 return Internal Error; check StoRM Backend info service status."
    yaimlog DEBUG "${FUNC}: set a temporary value."
    total=$(($4*(1000*1000*1000)))
    used=0
    free=$(($4*(1000*1000*1000)))
    reserved=0
    available=$(($4*(1000*1000*1000)))
  else
    # convert in byte (base 10)
    used=`echo $SIZE | sed -e 's/[{}]/''/g' | awk -v RS=',"' -F: '/^used-space/ {print $2}'`
    free=`echo $SIZE | sed -e 's/[{}]/''/g' | awk -v RS=',"' -F: '/^free-space/ {print $2}'`
    reserved=`echo $SIZE | sed -e 's/[{}]/''/g' | awk -v RS=',"' -F: '/^reserved-space/ {print $2}'`
    total=`echo $SIZE | sed -e 's/[{}]/''/g' | awk -v RS=',"' -F: '/^total-space/ {print $2}'`
    available=`echo $SIZE | sed -e 's/[{}]/''/g' | awk -v RS=',"' -F: '/^available-space/ {print $2}'`
    busy=`echo $SIZE | sed -e 's/[{}]/''/g' | awk -v RS=',"' -F: '/^busy-space/ {print $2}'`
    if [ "${available}" -eq "0" ]; then
      available=$((${total} - ${busy}))
    fi
    yaimlog DEBUG "${FUNC}: TOTAL: ${total}; AVAILABLE: ${available}; USED: ${used}; FREE: ${free}; RESERVED: ${reserved}; BUSY: $busy"
    NSIZE=`/usr/libexec/storm-dynamic-info-provider/storm-base-ten-converter -u $used -f $free -r $reserved -t $total -a $available`
    used=`echo $NSIZE | sed -e 's/[{}]/''/g' | awk -v RS=',' -F': ' '/used-space/ {print $2}'`
    free=`echo $NSIZE | sed -e 's/[{}]/''/g' | awk -v RS=',' -F': ' '/free-space/ {print $2}'`
    reserved=`echo $NSIZE | sed -e 's/[{}]/''/g' | awk -v RS=',' -F': ' '/reserved-space/ {print $2}'`
    total=`echo $NSIZE | sed -e 's/[{}]/''/g' | awk -v RS=',' -F': ' '/total-space/ {print $2}'`
    available=`echo $NSIZE | sed -e 's/[{}]/''/g' | awk -v RS=',' -F': ' '/available-space/ {print $2}'`
    yaimlog DEBUG "${FUNC}: TOTAL: ${total}; AVAILABLE: ${available}; USED: ${used}; FREE: ${free}; RESERVED: ${reserved}"
  fi
  yaimlog DEBUG "${FUNCTION}: TOTAL: ${total}; AVAILABLE: ${available}; USED: ${used}; FREE: ${free}; RESERVED: ${reserved}"
  export $5=${total}
  export $6=${available}
  export $7=${used}
  export $8=${free}
  export $9=${reserved}

  return 0

}

function config_gip_glue2_storm_check () {

  requires $1 SITE_NAME STORM_BACKEND_HOST STORM_DEFAULT_ROOT STORM_FRONTEND_PATH \
              STORM_FRONTEND_PORT STORM_FRONTEND_PUBLIC_HOST \
              STORM_BACKEND_REST_SERVICES_PORT VOS 
  return $?

}

function config_gip_glue2_storm_setenv () {

  yaimgridenv_set STORM_BACKEND_HOST ${STORM_BACKEND_HOST}
  yaimgridenv_set STORM_FRONTEND_PUBLIC_HOST ${STORM_FRONTEND_PUBLIC_HOST}
  yaimgridenv_set STORM_FRONTEND_PORT ${STORM_FRONTEND_PORT}
  yaimgridenv_set STORM_FRONTEND_PATH ${STORM_FRONTEND_PATH}
  yaimgridenv_set STORM_ENDPOINT_QUALITY_LEVEL ${STORM_ENDPOINT_QUALITY_LEVEL}
  yaimgridenv_set STORM_ENDPOINT_SERVING_STATE ${STORM_ENDPOINT_SERVING_STATE}
  yaimgridenv_set STORM_ENDPOINT_CAPABILITY ${STORM_ENDPOINT_CAPABILITY}

}

function config_gip_glue2_storm () {

  FUNCTION="config_gip_glue2_storm"

  INFO_SERVICE_CONFIG=/etc/glite/info/service
  INFO_SERVICE_SCRIPT=/usr/bin
  INFO_PROVIDER_PATH=/var/lib/bdii/gip/provider
  INFO_LDIF_PATH=/var/lib/bdii/gip/ldif
  INFO_PLUGIN_PATH=/var/lib/bdii/gip/plugin
  
  # Manage variables
  STORM_FRONTEND_ENDPOINT="httpg://${STORM_FRONTEND_PUBLIC_HOST}:${STORM_FRONTEND_PORT}${STORM_FRONTEND_PATH}"

  yaimlog INFO "${FUNCTION}: Static service information"
  #----------------------------------------------------------
  # ${INFO_PROVIDER_PATH}/service-glue2-srm-storm-v2 - BEGIN
  #----------------------------------------------------------
  FILE="${INFO_PROVIDER_PATH}/service-glue2-srm-storm-v2"
  yaimlog INFO "${FUNCTION}: Creating ${FILE} ..."
  cat > ${FILE} << EOF
#!/bin/sh
. /etc/profile.d/grid-env.sh
EOF

  cat >> ${FILE} << EOF
${INFO_SERVICE_SCRIPT}/glite-info-glue2-simple ${INFO_SERVICE_CONFIG}/glite-info-service-glue2-srm-storm-v2.conf ${SITE_NAME} ${STORM_FRONTEND_ENDPOINT}
EOF

  # Set execute permissions
  chmod +x ${FILE}
  yaimlog INFO "${FUNCTION}: Successfully created ${FILE} !"
  #--------------------------------------------------------
  # ${INFO_PROVIDER_PATH}/service-glue2-srm-storm-v2 - END
  #--------------------------------------------------------

  yaimlog INFO "${FUNCTION}: Static service information"
  #---------------------------------------------------------------------
  # ${INFO_SERVICE_CONFIG}/glite-info-service-glue2-srm-storm-v2.conf - BEGIN
  #---------------------------------------------------------------------
  # Configuration file for SRM v2.2 service reporter
  FILE="${INFO_SERVICE_CONFIG}/glite-info-service-glue2-srm-storm-v2.conf"
  yaimlog INFO "${FUNCTION}: Creating ${FILE} ..."

  ENDPOINT_QUALITY_LEVEL=`echo ${STORM_ENDPOINT_QUALITY_LEVEL}`
  ENDPOINT_SERVING_STATE=`echo ${STORM_ENDPOINT_SERVING_STATE}`

  cat > ${FILE} << EOF
init = /usr/libexec/storm-dynamic-info-provider/glite-info-service-storm init
service_type = SRM
get_version = echo \${GLITE_INFO_SERVICE_VERSION}
get_endpoint = echo \${GLITE_INFO_SERVICE_ENDPOINT}
get_status = ${INFO_SERVICE_SCRIPT}/glite-info-service-test SRM_V2 && /usr/libexec/storm-dynamic-info-provider/glite-info-service-storm status
WSDL_URL = http://sdm.lbl.gov/srm-wg/srm.v2.2.wsdl
semantics_URL = http://sdm.lbl.gov/srm-wg/doc/SRM.v2.2.html
get_starttime = perl -e '@st=stat("/var/run/storm-backend-server.pid");print "@st[10]\n";'

get_capabilities = echo -e 'data.management.storage'
get_implementor = echo emi
get_implementationname = echo StoRM
get_implementationversion = rpm -qa | grep storm-backend-server | cut -d- -f4
get_qualitylevel = echo $((ENDPOINT_QUALITY_LEVEL))
get_servingstate = echo $((ENDPOINT_SERVING_STATE))
get_data = echo
get_services = echo
EOF

  # Run function to complete file
  l_write_vo_info ${FILE}
  #-------------------------------------------------------------------------
  # ${INFO_SERVICE_CONFIG}/glite-info-service-glue2-srm-storm-v2.conf - END
  #-------------------------------------------------------------------------

  yaimlog INFO "${FUNCTION}: Static storage information"
  #----------------------------------------------------------------
  # ${INFO_LDIF_PATH}/static-file-glue2-storm.ldif - BEGIN
  #----------------------------------------------------------------
  FILE="${INFO_LDIF_PATH}/static-file-glue2-storm.ldif"   # Configuration filename
  FILE_B="${FILE}.bkp_`date +%Y%m%d_%H%M%S`"                     # Backup configuration filename (if needed)
  FILE_N="${FILE}.yaimnew_`date +%Y%m%d_%H%M%S`"                 # New configuration filename (if needed)

  # Configuration file management
  STORM_INFO_OVERWRITE=`echo ${STORM_INFO_OVERWRITE} | tr '[:upper:]' '[:lower:]'`   # convert in lowercase
  # If overwrite is enabled, create backup
  if [ "${STORM_INFO_OVERWRITE}" = "true" ]; then
    if [ -e ${FILE} ]; then
      yaimlog DEBUG "${FUNCTION}: Overwrite old configuration file ${FILE}"
      yaimlog DEBUG "${FUNCTION}: Backup old configuration file in ${FILE_B}"
      mv ${FILE} ${FILE_B}
    fi
  # Else if overwrite is disabled, create yaimnew
  else
    yaimlog DEBUG "${FUNCTION}: Not overwrite old configuration file ${FILE}"
    yaimlog DEBUG "${FUNCTION}: Create new configuration file in ${FILE_N}"
    FILE="${FILE_N}"
  fi
  touch ${FILE}

  yaimlog INFO "${FUNCTION}: Creating ${FILE} ..."

  # Remove oldest backup file
  yaimlog DEBUG "${FUNCTION}: Removing old backup files"
  find `dirname "${FILE}"` -ctime +2 -name 'static-file-glue2-storm.ldif.bkp*' -exec rm {} \;

  # Set permissions
  chmod 644 ${FILE}

  # Prepare need variables
  for SA in ${STORM_STORAGEAREA_LIST}; do

    # Convert case
    SA_UPP=`echo ${SA} | tr '[:lower:]' '[:upper:]'`
    SA_LOW=`echo ${SA} | tr '[:upper:]' '[:lower:]'`

    # Remove DNS-like characters from SA_UPP names
    SA_UPP=`echo ${SA_UPP} | sed -e 's/-//g' -e 's/\.//g'`

    x=STORM_${SA_UPP}_TOKEN;           SA_TOKEN=${!x:-${SA_UPP}_TOKEN}
    x=STORM_${SA_UPP}_QUOTA;           SA_QUOTA=${!x:-false}
    x=STORM_${SA_UPP}_ROOT;            SA_ROOT=${!x:-${STORM_DEFAULT_ROOT}/${SA_LOW}}
    x=STORM_${SA_UPP}_VONAME;          SA_VONAME=${!x:-${SA_LOW}}
    x=STORM_${SA_UPP}_STORAGECLASS;    SA_STORAGECLASS=${!x:-${STORM_STORAGECLASS}}

    hash_insert SA_TOTAL_ONLINE_SIZE_GB ${SA_UPP} 0          # default
    hash_insert SA_FREE_ONLINE_SIZE_GB  ${SA_UPP} 0           # default
    hash_insert SA_USED_ONLINE_SIZE_GB  ${SA_UPP} 0           # default
    hash_insert SA_RESERVED_ONLINE_SIZE_GB ${SA_UPP} 0      # default
    hash_insert SA_USED_ONLINE_SIZE_KB ${SA_UPP} 0           # default
    hash_insert SA_AVAILABLE_ONLINE_SIZE_KB ${SA_UPP} 0      # default

    hash_insert SA_TOTAL_NEARLINE_SIZE_GB ${SA_UPP} 0        # default

    x=STORM_${SA_UPP}_ONLINE_SIZE;   SA_SIZE=${!x}

    if ! [ -z "${SA_STORAGECLASS}" ]; then
      case ${SA_STORAGECLASS} in
        "T1D0")
          x=STORM_${SA_UPP}_NEARLINE_SIZE; SA_NL_SIZE=${!x}
          x=STORM_${SA_UPP}_ONLINE_SIZE;   SA_SIZE=${!x}
          ;;
        "T1D1")
          x=STORM_${SA_UPP}_ONLINE_SIZE;   SA_SIZE=${!x}
          ;;
        "T0D1")
          x=STORM_${SA_UPP}_ONLINE_SIZE;   SA_SIZE=${!x}
          ;;
        *)
          x=STORM_${SA_UPP}_ONLINE_SIZE;   SA_SIZE=${!x}
          ;;
      esac
    fi
    
    get_size ${SA_TOKEN} ${STORM_BACKEND_HOST} ${STORM_BACKEND_REST_SERVICES_PORT} ${SA_SIZE} TOTAL AVAILABLE USED FREE RESERVED

    if ! [ -z "${SA_STORAGECLASS}" ]; then
      if [ "${SA_STORAGECLASS}" == "T1D0" ] ; then
          # Get size values on SA_TOKEN (in GB)
          hash_insert SA_TOTAL_NEARLINE_SIZE_GB ${SA_UPP} ${SA_NL_SIZE}
      fi
    fi

    # Get size values on SA_TOKEN (in GB)
    hash_insert SA_USED_ONLINE_SIZE_GB  ${SA_UPP} $((${USED}/(1000*1000*1000)))
    hash_insert SA_FREE_ONLINE_SIZE_GB  ${SA_UPP} $((${FREE}/(1000*1000*1000)))
    hash_insert SA_TOTAL_ONLINE_SIZE_GB ${SA_UPP} $((${TOTAL}/(1000*1000*1000)))
    hash_insert SA_RESERVED_ONLINE_SIZE_GB ${SA_UPP} $((${RESERVED}/(1000*1000*1000)))

    # Get size values on SA_TOKEN (in KB)
    hash_insert SA_USED_ONLINE_SIZE_KB  ${SA_UPP} $((${USED}/1000))
    hash_insert SA_AVAILABLE_ONLINE_SIZE_KB  ${SA_UPP} $((${AVAILABLE}/1000))

    # Prepare per-VO and global values
    PERVO_VONAME_INDEX=`echo ${SA_VONAME} | sed -e 's/-//g' -e 's/\.//g'`
    # Add VONAME if missing
    if ! [[ "${PERVO_VONAMES}" =~ "${SA_VONAME}" ]]; then
      PERVO_VONAMES="${PERVO_VONAMES} ${SA_VONAME}"
      x=STORM_${SA_UPP}_ACCESSPOINT;   hash_insert PERVO_ACCESSPOINT ${PERVO_VONAME_INDEX} ${!x:-/${SA_LOW}}
    fi
    # Sum size values for VONAME and global(in GB)
    x=`hash_find PERVO_USED_ONLINE_SIZE_GB ${PERVO_VONAME_INDEX}`
    y=`hash_find SA_USED_ONLINE_SIZE_GB ${SA_UPP}`
    hash_insert PERVO_USED_ONLINE_SIZE_GB ${PERVO_VONAME_INDEX} $((x+y))
    let GLOBAL_USED_ONLINE_SIZE_GB+=$y

    x=`hash_find PERVO_RESERVED_ONLINE_SIZE_GB ${PERVO_VONAME_INDEX}`
    y=`hash_find SA_RESERVED_ONLINE_SIZE_GB ${SA_UPP}`
    hash_insert PERVO_RESERVED_ONLINE_SIZE_GB ${PERVO_VONAME_INDEX} $((x+y))
    let GLOBAL_RESERVED_ONLINE_SIZE_GB+=$y

    x=`hash_find PERVO_FREE_ONLINE_SIZE_GB ${PERVO_VONAME_INDEX}`
    y=`hash_find SA_FREE_ONLINE_SIZE_GB ${SA_UPP}`
    hash_insert PERVO_FREE_ONLINE_SIZE_GB ${PERVO_VONAME_INDEX} $((x+y))
    let GLOBAL_FREE_ONLINE_SIZE_GB+=$y

    x=`hash_find PERVO_TOTAL_ONLINE_SIZE_GB ${PERVO_VONAME_INDEX}`
    y=`hash_find SA_TOTAL_ONLINE_SIZE_GB ${SA_UPP}`
    hash_insert PERVO_TOTAL_ONLINE_SIZE_GB ${PERVO_VONAME_INDEX} $((x+y))
    let GLOBAL_TOTAL_ONLINE_SIZE_GB+=$y

    x=`hash_find PERVO_TOTAL_NEARLINE_SIZE_GB ${PERVO_VONAME_INDEX}`
    y=`hash_find SA_TOTAL_NEARLINE_SIZE_GB ${SA_UPP}`
    hash_insert PERVO_TOTAL_NEARLINE_SIZE_GB ${PERVO_VONAME_INDEX} $((x+y))
    let GLOBAL_TOTAL_NEARLINE_SIZE_GB+=$y

  done

  #==========================================================
  # Create GLUE2ServiceId entries

  yaimlog DEBUG "${FUNCTION}: Creating GLUE2ServiceId entries"
  cat >> ${FILE} << EOF
#
# GLUE2ServiceId
#
dn: GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupID=resource,o=glue
objectClass: GLUE2Service
objectClass: GLUE2StorageService
GLUE2ServiceId: ${STORM_FRONTEND_PUBLIC_HOST}
GLUE2ServiceCapability: ${STORM_ENDPOINT_CAPABILITY}
GLUE2ServiceType: Storage
GLUE2ServiceQualityLevel: ${STORM_ENDPOINT_QUALITY_LEVEL}
GLUE2ServiceStatusInfo: http://${STORM_FRONTEND_PUBLIC_HOST}/get-status
GLUE2ServiceAdminDomainForeignKey: ${MY_DOMAIN}

EOF
  #==========================================================

  #==========================================================
  # Create GLUE2StorageServiceCapacityId entries

  yaimlog DEBUG "${FUNCTION}: Creating GLUE2StorageServiceCapacityId entries"
  cat >> ${FILE} << EOF
#
# GLUE2StorageServiceCapacityId online
#
dn: GLUE2StorageServiceCapacityId=${STORM_FRONTEND_PUBLIC_HOST}/capacity/online,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2StorageServiceCapacity
GLUE2StorageServiceCapacityId: ${STORM_FRONTEND_PUBLIC_HOST}/capacity/online
GLUE2StorageServiceCapacityType: online
GLUE2StorageServiceCapacityTotalSize: $((GLOBAL_TOTAL_ONLINE_SIZE_GB))
GLUE2StorageServiceCapacityFreeSize: $((GLOBAL_FREE_ONLINE_SIZE_GB))
GLUE2StorageServiceCapacityUsedSize: $((GLOBAL_USED_ONLINE_SIZE_GB))
GLUE2StorageServiceCapacityReservedSize: $((GLOBAL_RESERVED_ONLINE_SIZE_GB))
GLUE2StorageServiceCapacityStorageServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/capacity/online

EOF

#==========================================================
  # Create GLUE2StorageServiceCapacityId entries

  yaimlog DEBUG "${FUNCTION}: Creating GLUE2StorageServiceCapacityId entries"
  cat >> ${FILE} << EOF
#
# GLUE2StorageServiceCapacityId nearline
#
dn: GLUE2StorageServiceCapacityId=${STORM_FRONTEND_PUBLIC_HOST}/capacity/nearline,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2StorageServiceCapacity
GLUE2StorageServiceCapacityId: ${STORM_FRONTEND_PUBLIC_HOST}/capacity/nearline
GLUE2StorageServiceCapacityType: nearline
GLUE2StorageServiceCapacityTotalSize: $((GLOBAL_TOTAL_NEARLINE_SIZE_GB))
GLUE2StorageServiceCapacityFreeSize: 0
GLUE2StorageServiceCapacityUsedSize: 0
GLUE2StorageServiceCapacityReservedSize: 0
GLUE2StorageServiceCapacityStorageServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/capacity/nearline

EOF

  #==========================================================
  # Create GLUE2EndpointId entries

  yaimlog DEBUG "${FUNCTION}: Creating GLUE2EndpointId entries"
  cat >> ${FILE} << EOF
#
# GLUE2EndpointId
#
dn: GLUE2EndpointId=${STORM_FRONTEND_PUBLIC_HOST}/srm/2.2.0,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupID=resource,o=glue
objectClass: GLUE2Endpoint
objectClass: GLUE2StorageEndpoint
GLUE2EndpointId: ${STORM_FRONTEND_PUBLIC_HOST}/srm/2.2.0
GLUE2EndpointURL: ${STORM_FRONTEND_ENDPOINT}
GLUE2EndpointCapability: Storage Management
GLUE2EndpointTechnology: webservice
GLUE2EndpointInterfaceName: SRM
GLUE2EndpointInterfaceVersion: 2.2.0
#GLUE2EndpointInterfaceExtension:
GLUE2EndpointWSDL: http://sdm.lbl.gov/srm-wg/srm.v2.2.wsdl
#GLUE2EndpointSupportedProfile:
GLUE2EndpointSemantics: http://sdm.lbl.gov/srm-wg/doc/srm.v2.2.wsdl
GLUE2EndpointImplementor: emi.storm
GLUE2EndpointImplementationName: StoRM
GLUE2EndpointImplementationVersion: `rpm -q --queryformat='%{VERSION}' storm-backend-server`
GLUE2EndpointQualityLevel: Testing
GLUE2EndpointHealthState: OK
GLUE2EndpointHealthStateInfo: No Problems for storm-backend-server
GLUE2EndpointServingState: emi.storm.backend
#GLUE2EndpointIssuerCA: to be defined
#GLUE2EndpointTrustedCA: to be defined
GLUE2EndpointDowntimeAnnounce: No
GLUE2EndpointServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}
GLUE2StorageEndpointStorageServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}

EOF

  #==========================================================
  # Create GLUE2ManagerId entries

  yaimlog DEBUG "${FUNCTION}: Creating GLUE2ManagerId entries"
  cat >> ${FILE} << EOF
#
# GLUE2ManagerId
#
dn: GLUE2ManagerID=${STORM_BACKEND_HOST}/manager,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupID=resource,o=glue
objectClass: GLUE2Manager
objectClass: GLUE2StorageManager
GLUE2ManagerId: ${STORM_BACKEND_HOST}/manager 
GLUE2ManagerProductName: storm-backend-server
GLUE2ManagerProductVersion: `rpm -q --queryformat='%{VERSION}' storm-backend-server`
GLUE2ManagerServiceForeignKey: ${STORM_BACKEND_HOST}
GLUE2StorageManagerStorageServiceForeignKey: ${STORM_BACKEND_HOST}

EOF

  #==========================================================
  # Create GLUE2Share entries

  for SA in ${STORM_STORAGEAREA_LIST}; do

    # Convert case
    SA_UPP=`echo ${SA} | tr '[:lower:]' '[:upper:]'`
    SA_LOW=`echo ${SA} | tr '[:upper:]' '[:lower:]'`

    # Remove DNS-like characters from SA_UPP names
    SA_UPP=`echo ${SA_UPP} | sed -e 's/-//g' -e 's/\.//g'`

    x=STORM_${SA_UPP}_ACCESSPOINT;     SA_ACCESSPOINT=${!x:-/${SA_LOW}}
    x=STORM_${SA_UPP}_TOKEN;           SA_TOKEN=${!x}
    x=STORM_${SA_UPP}_VONAME;          SA_VONAME=${!x:-${SA_LOW}}
    x=STORM_${SA_UPP}_STORAGECLASS;    SA_STORAGECLASS=${!x:-${STORM_STORAGECLASS}}
    x=STORM_${SA_UPP}_SERVINGSTATE;    SA_SERVING_STATE=${!x:-${STORM_ENDPOINT_SERVING_STATE}}
    # Convert in uppercase
    SA_STORAGECLASS=`echo ${SA_STORAGECLASS} | tr '[:lower:]' '[:upper:]'`

    # Check the STORAGECLASS
    SA_RETENTION_POLICY="replica"                                         # default
    SA_ACCESS_LATENCY="online"                                            # default
    SA_INSTALLED_ONLINE_CAPACITY=`hash_find SA_TOTAL_ONLINE_SIZE_GB ${SA_UPP}`   # default
    SA_INSTALLED_NEARLINE_CAPACITY=0                                      # default
    if ! [ -z "${SA_STORAGECLASS}" ]; then
      case ${SA_STORAGECLASS} in
        "T1D0")
          SA_RETENTION_POLICY="custodial"
          SA_ACCESS_LATENCY="nearline"
          SA_INSTALLED_ONLINE_CAPACITY=`hash_find SA_TOTAL_ONLINE_SIZE_GB ${SA_UPP}`
          SA_INSTALLED_NEARLINE_CAPACITY=`hash_find SA_TOTAL_NEARLINE_SIZE_GB ${SA_UPP}`
          ;;
        "T1D1")
          SA_RETENTION_POLICY="custodial"
          SA_ACCESS_LATENCY="online"
          SA_INSTALLED_ONLINE_CAPACITY=`hash_find SA_TOTAL_ONLINE_SIZE_GB ${SA_UPP}`
          SA_INSTALLED_NEARLINE_CAPACITY=0
          ;;
        "T0D1")
          SA_RETENTION_POLICY="replica"
          SA_ACCESS_LATENCY="online"
          SA_INSTALLED_ONLINE_CAPACITY=`hash_find SA_TOTAL_ONLINE_SIZE_GB ${SA_UPP}`
          SA_INSTALLED_NEARLINE_CAPACITY=0
          ;;
        *)
          SA_RETENTION_POLICY="replica"
          SA_ACCESS_LATENCY="online"
          SA_INSTALLED_ONLINE_CAPACITY=`hash_find SA_TOTAL_ONLINE_SIZE_GB ${SA_UPP}`
          SA_INSTALLED_NEARLINE_CAPACITY=0
          ;;
      esac
    fi

    #==========================================================
    # Create GLUE2PolicyId entries

    yaimlog DEBUG "${FUNCTION}: Creating GLUE2PolicyId entries"
    cat >> ${FILE} << EOF

#
# GLUE2PolicyID
#
dn: GLUE2PolicyID=${STORM_FRONTEND_PUBLIC_HOST}/srm/2.2.0/ap,GLUE2EndpointId=${STORM_FRONTEND_PUBLIC_HOST}/srm/2.2.0,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2Policy
objectClass: GLUE2AccessPolicy
GLUE2PolicyID: ${STORM_FRONTEND_PUBLIC_HOST}/srm/2.2.0/ap
GLUE2PolicyScheme: org.glite.standard
GLUE2PolicyRule: VO:${SA_VONAME}
GLUE2PolicyUserDomainForeignKey: ${SA_VONAME}
GLUE2AccessPolicyEndpointForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/srm/2.2.0/ap

EOF


    yaimlog DEBUG "${FUNCTION}: Creating GLUE2ShareID entries for ${SA_LOW} (${SA_VONAME} VO)"
    cat >> ${FILE} << EOF

#
# GLUE2ShareID ${SA_LOW} (${SA_VONAME} VO)
#
dn: GLUE2ShareId=${STORM_FRONTEND_PUBLIC_HOST}/${SA_LOW},GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2Share
objectClass: GLUE2StorageShare
GLUE2ShareId: ${STORM_FRONTEND_PUBLIC_HOST}/${SA_LOW}
GLUE2ShareDescription: Share for ${SA_VONAME}
GLUE2StorageShareServingState: ${SA_SERVING_STATE}
GLUE2StorageSharePath: ${SA_ACCESSPOINT}
#GLUE2StorageShareAccessMode: to be defined
GLUE2StorageShareSharingID: ${SA_VONAME}:${SA_RETENTION_POLICY}:${SA_ACCESS_LATENCY}
GLUE2StorageShareAccessLatency: ${SA_ACCESS_LATENCY}
GLUE2StorageShareRetentionPolicy: ${SA_RETENTION_POLICY}
GLUE2StorageShareExpirationMode: neverExpire
GLUE2StorageShareDefaultLifeTime: -1
GLUE2StorageShareMaximumLifeTime: -1
GLUE2StorageShareTag: ${SA_LOW}
GLUE2ShareServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}
GLUE2StorageShareStorageServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/${SA_LOW}

EOF

    yaimlog DEBUG "${FUNCTION}: Creating GLUE2StorageShareCapacityID entries for ${SA_LOW} (${SA_VONAME} VO)"

    SA_TOTAL_SIZE_GB=$(($((`hash_find SA_TOTAL_ONLINE_SIZE_GB ${SA_UPP}`))+$((`hash_find SA_TOTAL_NEARLINE_SIZE_GB ${SA_UPP}`))))
    yaimlog DEBUG "${FUNCTION}: Check TOTAL_SIZE_GB ${SA_TOTAL_SIZE_GB}"
    cat >> ${FILE} << EOF

#
# GLUE2StorageShareCapacityID ${SA_LOW} (${SA_VONAME} VO)
#
dn: GLUE2StorageShareCapacityID=${STORM_FRONTEND_PUBLIC_HOST}/${SA_LOW}/capacity,GLUE2ShareId=${STORM_FRONTEND_PUBLIC_HOST}/${SA_LOW},GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2StorageShareCapacity
GLUE2StorageShareCapacityID: ${STORM_FRONTEND_PUBLIC_HOST}/${SA_LOW}/capacity
GLUE2StorageShareCapacityType: ${SA_ACCESS_LATENCY}
GLUE2StorageShareCapacityTotalSize: $((SA_TOTAL_SIZE_GB)) 
GLUE2StorageShareCapacityFreeSize: $((`hash_find SA_FREE_ONLINE_SIZE_GB ${SA_UPP}`))
GLUE2StorageShareCapacityUsedSize: $((`hash_find SA_USED_ONLINE_SIZE_GB ${SA_UPP}`))
GLUE2StorageShareCapacityReservedSize: $((`hash_find SA_RESERVED_ONLINE_SIZE_GB ${SA_UPP}`))
GLUE2StorageShareCapacityStorageShareForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/${SA_LOW}/capacity

EOF

  done
  
  #==========================================================

  #==========================================================
  # Create GlueSEAccessProtocol entries

  # Convert in lowercase
  STORM_INFO_FILE_SUPPORT=`echo ${STORM_INFO_FILE_SUPPORT} | tr '[:upper:]' '[:lower:]'`
  STORM_INFO_RFIO_SUPPORT=`echo ${STORM_INFO_RFIO_SUPPORT} | tr '[:upper:]' '[:lower:]'`
  STORM_INFO_GRIDFTP_SUPPORT=`echo ${STORM_INFO_GRIDFTP_SUPPORT} | tr '[:upper:]' '[:lower:]'`
  STORM_INFO_ROOT_SUPPORT=`echo ${STORM_INFO_ROOT_SUPPORT} | tr '[:upper:]' '[:lower:]'`
  STORM_INFO_HTTP_SUPPORT=`echo ${STORM_INFO_HTTP_SUPPORT} | tr '[:upper:]' '[:lower:]'`
  STORM_INFO_HTTPS_SUPPORT=`echo ${STORM_INFO_HTTPS_SUPPORT} | tr '[:upper:]' '[:lower:]'`

  if [ ${STORM_INFO_FILE_SUPPORT} = "true" ]; then
    yaimlog DEBUG "${FUNCTION}: Creating GLUE2StorageAccessProtocolID entries for file protocol"
    cat >> ${FILE} << EOF
#
# GLUE2StorageAccessProtocolID file
#
dn: GLUE2StorageAccessProtocolID=${STORM_FRONTEND_PUBLIC_HOST}/file,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2StorageAccessProtocol
GLUE2StorageAccessProtocolID: ${STORM_FRONTEND_PUBLIC_HOST}/file
GLUE2StorageAccessProtocolType: file
GLUE2StorageAccessProtocolVersion: 1.0.0
GLUE2StorageAccessProtocolMaxStreams: 1
GLUE2StorageAccessProtocolStorageServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/file

EOF
  fi

  if [ ${STORM_INFO_RFIO_SUPPORT} = "true" ]; then
    yaimlog DEBUG "${FUNCTION}: Creating GLUE2StorageAccessProtocolID entries for rfio protocol"
    cat >> ${FILE} << EOF
#
# GLUE2StorageAccessProtocolID rfio
#
dn: GLUE2StorageAccessProtocolID=${STORM_FRONTEND_PUBLIC_HOST}/rfio,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2StorageAccessProtocol
GLUE2StorageAccessProtocolID: ${STORM_FRONTEND_PUBLIC_HOST}/rfio
GLUE2StorageAccessProtocolType: rfio
GLUE2StorageAccessProtocolVersion: 1.0.0
GLUE2StorageAccessProtocolMaxStreams: 1
GLUE2StorageAccessProtocolStorageServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/rfio

EOF
  fi

  if [ ${STORM_INFO_GRIDFTP_SUPPORT} = "true" ]; then
    yaimlog DEBUG "${FUNCTION}: Creating GLUE2StorageAccessProtocolID entries for gsiftp protocol"
    cat >> ${FILE} << EOF
#
# GLUE2StorageAccessProtocolID gsiftp
#
dn: GLUE2StorageAccessProtocolID=${STORM_FRONTEND_PUBLIC_HOST}/gsiftp,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2StorageAccessProtocol
GLUE2StorageAccessProtocolID: ${STORM_FRONTEND_PUBLIC_HOST}/gsiftp
GLUE2StorageAccessProtocolType: gsiftp
GLUE2StorageAccessProtocolVersion: 2.0.0
GLUE2StorageAccessProtocolMaxStreams: 10
GLUE2StorageAccessProtocolStorageServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/gsiftp

EOF
  fi

  if [ ${STORM_INFO_ROOT_SUPPORT} = "true" ]; then
    yaimlog DEBUG "${FUNCTION}: Creating GLUE2StorageAccessProtocolID entries for root protocol"
    cat >> ${FILE} << EOF
#
# GLUE2StorageAccessProtocolID root
#
dn: GLUE2StorageAccessProtocolID=${STORM_FRONTEND_PUBLIC_HOST}/root,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2StorageAccessProtocol
GLUE2StorageAccessProtocolID: ${STORM_FRONTEND_PUBLIC_HOST}/root
GLUE2StorageAccessProtocolType: root
GLUE2StorageAccessProtocolVersion: 1.0.0
GLUE2StorageAccessProtocolMaxStreams: 1
GLUE2StorageAccessProtocolStorageServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/root

EOF
  fi

  if [ ${STORM_INFO_HTTP_SUPPORT} = "true" ]; then
    yaimlog DEBUG "${FUNCTION}: Creating GLUE2StorageAccessProtocolID entries for http protocol"
    cat >> ${FILE} << EOF
#
# GLUE2StorageAccessProtocolID http
#
dn: GLUE2StorageAccessProtocolID=${STORM_FRONTEND_PUBLIC_HOST}/http,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2StorageAccessProtocol
GLUE2StorageAccessProtocolID: ${STORM_FRONTEND_PUBLIC_HOST}/http
GLUE2StorageAccessProtocolType: http
GLUE2StorageAccessProtocolVersion: 1.1.0
GLUE2StorageAccessProtocolMaxStreams: 1
GLUE2StorageAccessProtocolStorageServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/http

EOF
  fi

    if [ ${STORM_INFO_HTTPS_SUPPORT} = "true" ]; then
    yaimlog DEBUG "${FUNCTION}: Creating GLUE2StorageAccessProtocolID  entries for https protocol"
    cat >> ${FILE} << EOF
#
# GLUE2StorageAccessProtocolID https
#
dn: GLUE2StorageAccessProtocolID=${STORM_FRONTEND_PUBLIC_HOST}/https,GLUE2ServiceId=${STORM_FRONTEND_PUBLIC_HOST},GLUE2GroupId=resource,o=glue
objectClass: GLUE2StorageAccessProtocol
GLUE2StorageAccessProtocolID: ${STORM_FRONTEND_PUBLIC_HOST}/https
GLUE2StorageAccessProtocolType: https
GLUE2StorageAccessProtocolVersion: 1.1.0
GLUE2StorageAccessProtocolMaxStreams: 1
GLUE2StorageAccessProtocolStorageServiceForeignKey: ${STORM_FRONTEND_PUBLIC_HOST}/https

EOF
  fi
  #==========================================================

  chown ldap:ldap ${FILE}
  yaimlog INFO "${FUNCTION}: Successfully created ${FILE} !"
  #----------------------------------------------------------------
  # ${INFO_LDIF_PATH}/static-file-glue2-storm.ldif - END
  #---------------------------------------------------------------

  #--------------------------------------------------------------------
  # Create configuration file for dynamic information provider
  FILE="/etc/storm/backend-server/storm-yaim-variables.conf"
  yaimlog INFO "${FUNCTION}: Creating ${FILE} ..."
  set | egrep '^STORM|^SITE_NAME' | sort > ${FILE}
  chgrp ldap /etc/storm/backend-server/storm-yaim-variables.conf
  chmod 450 ${FILE}

  #--------------------------------------------------------------------
  # ${INFO_PLUGIN_PATH}/glite-info-glue2-dynamic-storm  - BEGIN
  #--------------------------------------------------------------------
  yaimlog INFO "${FUNCTION}: Dynamic storage information"
  # Install dynamic script pointing to gip plugin
  WRAPPER="${INFO_PLUGIN_PATH}/glite-info-glue2-dynamic-storm"
  yaimlog INFO "${FUNCTION}: Creating ${WRAPPER} ..."
  cat > ${WRAPPER} << EOF
#! /bin/sh
/usr/libexec/storm-dynamic-info-provider/glite-info-glue2-dynamic-storm ${FILE}
EOF
  chown ldap:ldap ${WRAPPER}

  # Set permissions
  chmod 755 ${WRAPPER}
  #--------------------------------------------------------------------
  # ${INFO_PLUGIN_PATH}/glite-info-glue2-dynamic-storm - END
  #--------------------------------------------------------------------

  # Remove old cron replaced by new dynamic information provider
  rm -f /etc/cron.d/glite-info-glue2-dynamic-storm

  # Exit with success
  return 0

}
