#!/bin/bash
#
# 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.
#
# Authors: 
#      Akos Frohner <Akos.Frohner@cern.ch>
#

#
# Produces FTS service information for various information systems.
#

base=$(cd $(dirname $0); pwd)
TOMCAT_XSLT=$base/$(basename $0)-tomcat.xsl
CHANNELSQL=$base/$(basename $0)-channelinfo.sql

if [ -f /var/glite-data-transfer-fts-info-provider.dbparams ]; then 
	DBPARAMFILE=/var/glite-data-transfer-fts-info-provider.dbparams
else
	DBPARAMFILE=/opt/glite/var/glite-data-transfer-fts-info-provider.dbparams
fi


USAGE=$(basename $0)" (--bdii|--file) [--channels] [--site site_name] {--vo VO_name} [--myproxy service_name] [--hostalias hostname] [--verbose] [--help]"

TEMP=$(getopt -o hcAbfv:s:m:a:V --long help,channels,bdii,file,vo:,site:,myproxy:,hostalias:,verbose -- "$@")
eval set -- "$TEMP"

# by default it is 'bdii', but can also be 'file'
INFOSYS='bdii'
# by default the VO list is empty
VOS=""
# the default site is the domain name of the host
SITE=$(hostname --domain)

# system default
[ -r /etc/tomcat5/tomcat5.conf ] && source /etc/tomcat5/tomcat5.conf
# RedHat settings
[ -r /etc/sysconfig/tomcat5 ] && source /etc/sysconfig/tomcat5

for TOMCAT_CONF in ${CATALINA_HOME}/conf /var/tomcat5/conf /var/lib/tomcat5/conf /etc/tomcat5; do
    if [ -r ${TOMCAT_CONF}/server.xml ]; then
        break
    fi
done
if [ ! -r "$TOMCAT_CONF/server.xml" ]; then
    echo "ERROR: could not find Tomcat5 configuration directory!" >&2
    exit 1
fi

# by default quiet operation
VERBOSE='false'
# if unset after processing the parameters, defaults to hostname
unset HOSTALIASES
# by default do not publish channels (backward compatibility)
PUBLISH_CHANNELS='false'
# by default MyProxy association is not published
MYPROXY_NAME=""
# refactored options for the sake of XML: no --
OPTIONS=''

while true; do
    case "$1" in
        -f|--file)
            INFOSYS='file'
            OPTIONS="$OPTIONS -f"
            shift
            ;;
        -b|--bdii)
            INFOSYS='bdii'
            OPTIONS="$OPTIONS -b"
            shift
            ;;
        -v|--vo)
            shift
            VOS="$VOS $1"
            OPTIONS="$OPTIONS -v '$1'"
            shift
            ;;
        -s|--site)
            shift
            SITE="$1"
            OPTIONS="$OPTIONS -s '$1'"
            shift
            ;;
        -m|--myproxy)
            shift
            MYPROXY_NAME="$1"
            OPTIONS="$OPTIONS -m '$1'"
            shift
            ;;
        -a|--hostalias)
            shift
            HOSTALIASES="$HOSTALIASES $1"
            OPTIONS="$OPTIONS -a '$1'"
            shift
            ;;
        -c|--channels)
            PUBLISH_CHANNELS='true'
            OPTIONS="$OPTIONS -c"
            shift
            ;;
        -V|--verbose)
            VERBOSE='true'
            OPTIONS="$OPTIONS -V"
            shift
            ;;
        -h|--help)
            echo $USAGE
            exit
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "Unknown option '$1'"
            exit
            ;;
    esac
done

# setting to default, unless set
if [ -z "$HOSTALIASES" ]; then
   HOSTALIASES=$(hostname --fqdn)
fi

#######################################################################
# printing information

function print_start {
    if [ "$INFOSYS" = "bdii" ]; then
        echo "# Produced by "$(basename $0)" on "$(hostname --fqdn)
        echo "# with options: $0 $OPTIONS"
    elif [ "$INFOSYS" = "file" ]; then
        cat <<EOF
<!DOCTYPE services
    PUBLIC "-//gLite//DTD glite-service-discovery-file 1.0//EN"
    "http://egee-jra1-data.web.cern.ch/egee-jra1-data/dtd/service-discovery/1.0/services.dtd">
<!-- Produced by $(basename $0) on $(hostname --fqdn) -->
<!-- with options: $0 $OPTIONS -->
<services>
EOF
    else
        echo "ERROR: unknown information system: '$INFOSYS'" >&2
        exit 1
    fi
}

function print_end {
    if [ "$INFOSYS" = "bdii" ]; then
        echo ""
    elif [ "$INFOSYS" = "file" ]; then
        echo "</services>"
    else
        echo "ERROR: unknown information system: '$INFOSYS'" >&2
        exit 1
    fi
}

function print_service {
    if [ "$INFOSYS" = "bdii" ]; then
        print_service_bdii "$@"
    elif [ "$INFOSYS" = "file" ]; then
        print_service_file "$@"
    else
        echo "ERROR: unknown information system: '$INFOSYS'" >&2
        exit 1
    fi
}


function print_service_glue2 {
    if [ "$INFOSYS" = "bdii" ]; then
        print_service_bdii_glue2 "$@"
    elif [ "$INFOSYS" = "file" ]; then
        print_service_file_glue2 "$@"
    else
        echo "ERROR: unknown information system: '$INFOSYS'" >&2
        exit 1
    fi
}



function print_service_bdii {
NAME="$1"
ENDPOINT="$2"
cat <<EOF
dn: GlueServiceUniqueID=${NAME}_org.glite.FileTransfer,Mds-vo-name=resource,o=grid
objectClass: GlueTop
objectClass: GlueService
objectClass: GlueSchemaVersion
objectClass: GlueKey
GlueServiceUniqueID: ${NAME}_org.glite.FileTransfer
GlueServiceName: $NAME
GlueServiceType: org.glite.FileTransfer
GlueServiceVersion: $VERSION
GlueServiceEndpoint: $ENDPOINT/services/FileTransfer
GlueServiceWSDL: $ENDPOINT/services/FileTransfer?wsdl
GlueServiceAccessPointURL: $ENDPOINT/services/FileTransfer?wsdl
GlueServiceSemantics: normal
GlueServiceStartTime: $DATE
GlueServiceStatus: $SERVICE_STATUS
GlueForeignKey: GlueServiceUniqueID=${NAME}_org.glite.ChannelManagement
GlueForeignKey: GlueServiceUniqueID=${NAME}_org.glite.Delegation
GlueSchemaVersionMajor: 1
GlueSchemaVersionMinor: 2
EOF
if [ -n "$MYPROXY_NAME" ]; then
    echo "GlueForeignKey: GlueServiceUniqueID=${MYPROXY_NAME}"
fi
if [ -n "$SITE" ]; then
    echo "GlueForeignKey: GlueSiteUniqueId=$SITE"
fi
for vo in $VOS; do 
    echo "GlueServiceOwner: $vo"
    echo "GlueServiceAccessControlRule: $vo"
done
for vo in $VOS; do 
    echo "GlueServiceAccessControlBaseRule: VO:$vo"
done



# end-of-ldif-record
echo ""

cat <<EOF
dn: GlueServiceUniqueID=${NAME}_org.glite.ChannelManagement,Mds-vo-name=resource,o=grid
objectClass: GlueTop
objectClass: GlueService
objectClass: GlueSchemaVersion
objectClass: GlueKey
GlueServiceUniqueID: ${NAME}_org.glite.ChannelManagement
GlueServiceName: $NAME-channel
GlueServiceType: org.glite.ChannelManagement
GlueServiceVersion: $VERSION
GlueServiceEndpoint: $ENDPOINT/services/ChannelManagement
GlueServiceWSDL: $ENDPOINT/services/ChannelManagement?wsdl
GlueServiceAccessPointURL: $ENDPOINT/services/ChannelManagement?wsdl
GlueServiceSemantics: normal
GlueServiceStartTime: $DATE
GlueServiceStatus: $SERVICE_STATUS
GlueForeignKey: GlueServiceUniqueID=${NAME}_org.glite.FileTransfer
GlueForeignKey: GlueServiceUniqueID=${NAME}_org.glite.Delegation
GlueSchemaVersionMajor: 1
GlueSchemaVersionMinor: 2
EOF
if [ -n "$SITE" ]; then
    echo "GlueForeignKey: GlueSiteUniqueId=$SITE"
fi
for vo in $VOS; do 
    echo "GlueServiceOwner: $vo"
    echo "GlueServiceAccessControlRule: $vo"
done
for vo in $VOS; do 
    echo "GlueServiceAccessControlBaseRule: VO:$vo"
done


# end-of-ldif-record
echo ""

cat <<EOF
dn: GlueServiceUniqueID=${NAME}_org.glite.Delegation,Mds-vo-name=resource,o=grid
objectClass: GlueTop
objectClass: GlueService
objectClass: GlueSchemaVersion
objectClass: GlueKey
GlueServiceUniqueID: ${NAME}_org.glite.Delegation
GlueServiceName: $NAME-delegation
GlueServiceType: org.glite.Delegation
GlueServiceVersion: $VERSION
GlueServiceEndpoint: $ENDPOINT/services/gridsite-delegation
GlueServiceWSDL: $ENDPOINT/services/gridsite-delegation?wsdl
GlueServiceAccessPointURL: $ENDPOINT/services/gridsite-delegation?wsdl
GlueServiceSemantics: normal
GlueServiceStartTime: $DATE
GlueServiceStatus: $SERVICE_STATUS
GlueForeignKey: GlueServiceUniqueID=${NAME}_org.glite.FileTransfer
GlueForeignKey: GlueServiceUniqueID=${NAME}_org.glite.ChannelManagement
GlueSchemaVersionMajor: 1
GlueSchemaVersionMinor: 2
EOF
if [ -n "$SITE" ]; then
    echo "GlueForeignKey: GlueSiteUniqueId=$SITE"
fi
for vo in $VOS; do 
    echo "GlueServiceOwner: $vo"
    echo "GlueServiceAccessControlRule: $vo"
done
for vo in $VOS; do 
    echo "GlueServiceAccessControlBaseRule: VO:$vo"
done

# end-of-ldif-record
echo ""
}

function print_service_file {
NAME="$1"
ENDPOINT="$2"
cat <<EOF
  <service name='${NAME}_org.glite.FileTransfer'>
    <parameters>
      <endpoint>$ENDPOINT/services/FileTransfer</endpoint>
      <type>org.glite.FileTransfer</type>
      <version>$VERSION</version>
      <wsdl>$ENDPOINT/services/FileTransfer?wsdl</wsdl>
EOF
if [ -n "$SITE" ]; then
    echo "      <site>$SITE</site>"
fi
if [ -n "$VOS" ]; then
    echo '      <volist>'
    for vo in $VOS; do echo "        <vo>$vo</vo>"; done
    echo '      </volist>'
fi
cat <<EOF
    </parameters>
    <associatedservices>
      <name>${NAME}_org.glite.ChannelManagement</name>
      <name>${NAME}_org.glite.Delegation</name>
EOF
if [ -n "$MYPROXY_NAME" ]; then
    echo "      <name>${MYPROXY_NAME}</name>"
fi
cat <<EOF
    </associatedservices>
  </service>
  <service name='${NAME}_org.glite.ChannelManagement'>
    <parameters>
      <endpoint>$ENDPOINT/services/ChannelManagement</endpoint>
      <type>org.glite.ChannelManagement</type>
      <version>$VERSION</version>
      <wsdl>$ENDPOINT/services/ChannelManagement?wsdl</wsdl>
EOF
if [ -n "$SITE" ]; then
    echo "      <site>$SITE</site>"
fi
if [ -n "$VOS" ]; then
    echo '      <volist>'
    for vo in $VOS; do echo "        <vo>$vo</vo>"; done
    echo '      </volist>'
fi
cat <<EOF
    </parameters>
    <associatedservices>
      <name>${NAME}_org.glite.FileTransfer</name>
      <name>${NAME}_org.glite.Delegation</name>
    </associatedservices>
  </service>
  <service name='${NAME}_org.glite.Delegation'>
    <parameters>
      <endpoint>$ENDPOINT/services/gridsite-delegation</endpoint>
      <type>org.glite.Delegation</type>
      <version>$VERSION</version>
      <wsdl>$ENDPOINT/services/gridsite-delegation?wsdl</wsdl>
EOF
if [ -n "$SITE" ]; then
    echo "      <site>$SITE</site>"
fi
if [ -n "$VOS" ]; then
    echo '      <volist>'
    for vo in $VOS; do echo "        <vo>$vo</vo>"; done
    echo '      </volist>'
fi
cat <<EOF
    </parameters>
    <associatedservices>
      <name>${NAME}_org.glite.FileTransfer</name>
      <name>${NAME}_org.glite.ChannelManagement</name>
    </associatedservices>
  </service>
EOF
}




##########################GLUE2 STUFF START##################################
function print_service_bdii_glue2 {
NAME="$1"
ENDPOINT="$2"
cat <<EOF

dn: GLUE2ServiceID=${ENDPOINT}_org.glite.fts,GLUE2GroupID=resource,o=glue
GLUE2ServiceID: ${ENDPOINT}_org.glite.fts
objectClass: GLUE2Service
GLUE2ServiceType: org.glite.fts
GLUE2ServiceQualityLevel: production
GLUE2ServiceAdminDomainForeignKey: CERN-PROD

dn: GLUE2EndpointID=${NAME}_org.glite.FileTransfer,GLUE2ServiceID=${ENDPOINT}_org.glite.fts,GLUE2GroupID=resource,o=glue
objectClass: GLUE2Endpoint
GLUE2EndpointID:  ${NAME}_org.glite.FileTransfer
GLUE2EndpointInterfaceVersion: $VERSION
GLUE2EndpointQualityLevel: production
GLUE2EndpointInterfaceName: org.glite.FileTransfer
GLUE2EndpointSemantics: https://twiki.cern.ch/twiki/bin/view/EGEE/FTS
GLUE2EndpointURL: $ENDPOINT/services/FileTransfer
GLUE2EndpointWSDL: $ENDPOINT/services/FileTransfer?wsdl
GLUE2EndpointStartTime: $DATE_GLUE2
GLUE2EndpointHealthState: $SERVICE_STATUS_GLUE2
GLUE2EndpointServingState: production
GLUE2EndpointServiceForeignKey: ${ENDPOINT}_org.glite.fts
EOF

echo ""
echo "dn: GLUE2PolicyID=${NAME}_org.glite.FileTransfer_policy,GLUE2EndpointID=${NAME}_org.glite.FileTransfer,GLUE2ServiceID=${ENDPOINT}_org.glite.fts,GLUE2GroupID=resource,o=glue"
echo "objectClass: GLUE2Policy"
echo "objectClass: GLUE2AccessPolicy"
echo "GLUE2PolicyID: ${NAME}_org.glite.FileTransfer_policy"
echo "GLUE2EntityCreationTime: $DATE_GLUE2"
echo "GLUE2PolicyScheme: org.glite.standard"
for vo in $VOS; do 
echo "GLUE2PolicyRule: VO:$vo"
echo "GLUE2PolicyUserDomainForeignKey: $vo"
done
echo "GLUE2AccessPolicyEndpointForeignKey: ${NAME}_org.glite.FileTransfer"


# end-of-ldif-record
echo ""

cat <<EOF

dn: GLUE2EndpointID=${NAME}_org.glite.ChannelManagement,GLUE2ServiceID=${ENDPOINT}_org.glite.fts,GLUE2GroupID=resource, o=glue
objectClass: GLUE2Endpoint
GLUE2EndpointID: ${NAME}_org.glite.ChannelManagement
GLUE2EndpointInterfaceVersion: $VERSION
GLUE2EndpointQualityLevel: production
GLUE2EndpointInterfaceName: org.glite.ChannelManagement
GLUE2EndpointSemantics: https://twiki.cern.ch/twiki/bin/view/EGEE/FTS
GLUE2EndpointURL: $ENDPOINT/services/ChannelManagement
GLUE2EndpointWSDL: $ENDPOINT/services/ChannelManagement?wsdl
GLUE2EndpointStartTime: $DATE_GLUE2
GLUE2EndpointHealthState: $SERVICE_STATUS_GLUE2
GLUE2EndpointServingState: production
GLUE2EndpointServiceForeignKey: ${ENDPOINT}_org.glite.fts
EOF

echo ""
echo "dn: GLUE2PolicyID=${NAME}_org.glite.ChannelManagement_policy,GLUE2EndpointID=${NAME}_org.glite.ChannelManagement,GLUE2ServiceID=${ENDPOINT}_org.glite.fts,GLUE2GroupID=resource,o=glue"
echo "objectClass: GLUE2Policy"
echo "objectClass: GLUE2AccessPolicy"
echo "GLUE2PolicyID: ${NAME}_org.glite.ChannelManagement_policy"
echo "GLUE2EntityCreationTime: $DATE_GLUE2"
echo "GLUE2PolicyScheme: org.glite.standard"
for vo in $VOS; do 
echo "GLUE2PolicyRule: VO:$vo"
echo "GLUE2PolicyUserDomainForeignKey: $vo"
done
echo "GLUE2AccessPolicyEndpointForeignKey: ${NAME}_org.glite.ChannelManagement"

# end-of-ldif-record
echo ""

cat <<EOF

dn: GLUE2EndpointID=${NAME}_org.glite.Delegation,GLUE2ServiceID=${ENDPOINT}_org.glite.fts,GLUE2GroupID=resource,o=glue
objectClass: GLUE2Endpoint
GLUE2EndpointID: ${NAME}_org.glite.Delegation
GLUE2EndpointInterfaceVersion: $VERSION
GLUE2EndpointQualityLevel: production
GLUE2EndpointInterfaceName: org.glite.Delegation
GLUE2EndpointSemantics: https://twiki.cern.ch/twiki/bin/view/EGEE/FTS
GLUE2EndpointURL: $ENDPOINT/services/gridsite-delegation
GLUE2EndpointWSDL: $ENDPOINT/services/gridsite-delegation?wsdl
GLUE2EndpointStartTime: $DATE_GLUE2
GLUE2EndpointHealthState: $SERVICE_STATUS_GLUE2
GLUE2EndpointServingState: production
GLUE2EndpointServiceForeignKey: ${ENDPOINT}_org.glite.fts
EOF

echo ""
echo "dn: GLUE2PolicyID=${NAME}_org.glite.Delegation_policy,GLUE2EndpointID=${NAME}_org.glite.Delegation,GLUE2ServiceID=${ENDPOINT}_org.glite.fts,GLUE2GroupID=resource,o=glue"
echo "objectClass: GLUE2Policy"
echo "objectClass: GLUE2AccessPolicy"
echo "GLUE2PolicyID: ${NAME}_org.glite.Delegation_policy"
echo "GLUE2EntityCreationTime: $DATE_GLUE2"
echo "GLUE2PolicyScheme: org.glite.standard"
for vo in $VOS; do 
echo "GLUE2PolicyRule: VO:$vo"
echo "GLUE2PolicyUserDomainForeignKey: $vo"
done
echo "GLUE2AccessPolicyEndpointForeignKey: ${NAME}_org.glite.Delegation"


# end-of-ldif-record
echo ""
}

function print_service_file_glue2 {
NAME="$1"
ENDPOINT="$2"
cat <<EOF
  <service name='${NAME}_org.glite.FileTransfer'>
    <parameters>
      <endpoint>$ENDPOINT/services/FileTransfer</endpoint>
      <type>org.glite.FileTransfer</type>
      <version>$VERSION</version>
      <wsdl>$ENDPOINT/services/FileTransfer?wsdl</wsdl>
EOF
if [ -n "$SITE" ]; then
    echo "      <site>$SITE</site>"
fi
if [ -n "$VOS" ]; then
    echo '      <volist>'
    for vo in $VOS; do echo "        <vo>$vo</vo>"; done
    echo '      </volist>'
fi
cat <<EOF
    </parameters>
    <associatedservices>
      <name>${NAME}_org.glite.ChannelManagement</name>
      <name>${NAME}_org.glite.Delegation</name>
EOF
if [ -n "$MYPROXY_NAME" ]; then
    echo "      <name>${MYPROXY_NAME}</name>"
fi
cat <<EOF
    </associatedservices>
  </service>
  <service name='${NAME}_org.glite.ChannelManagement'>
    <parameters>
      <endpoint>$ENDPOINT/services/ChannelManagement</endpoint>
      <type>org.glite.ChannelManagement</type>
      <version>$VERSION</version>
      <wsdl>$ENDPOINT/services/ChannelManagement?wsdl</wsdl>
EOF
if [ -n "$SITE" ]; then
    echo "      <site>$SITE</site>"
fi
if [ -n "$VOS" ]; then
    echo '      <volist>'
    for vo in $VOS; do echo "        <vo>$vo</vo>"; done
    echo '      </volist>'
fi
cat <<EOF
    </parameters>
    <associatedservices>
      <name>${NAME}_org.glite.FileTransfer</name>
      <name>${NAME}_org.glite.Delegation</name>
    </associatedservices>
  </service>
  <service name='${NAME}_org.glite.Delegation'>
    <parameters>
      <endpoint>$ENDPOINT/services/gridsite-delegation</endpoint>
      <type>org.glite.Delegation</type>
      <version>$VERSION</version>
      <wsdl>$ENDPOINT/services/gridsite-delegation?wsdl</wsdl>
EOF
if [ -n "$SITE" ]; then
    echo "      <site>$SITE</site>"
fi
if [ -n "$VOS" ]; then
    echo '      <volist>'
    for vo in $VOS; do echo "        <vo>$vo</vo>"; done
    echo '      </volist>'
fi
cat <<EOF
    </parameters>
    <associatedservices>
      <name>${NAME}_org.glite.FileTransfer</name>
      <name>${NAME}_org.glite.ChannelManagement</name>
    </associatedservices>
  </service>
EOF
}

##############################GLUE2 STUFF END############################################################33


function print_channel {
    if [ "$INFOSYS" = "bdii" ]; then
        print_channel_bdii "$@"	
    elif [ "$INFOSYS" = "file" ]; then
        print_channel_file "$@"
    else
        echo "ERROR: unknown information system: '$INFOSYS'" >&2
        exit 1
    fi
}


function print_channel_glue2 {
    if [ "$INFOSYS" = "bdii" ]; then
        print_channel_bdii_glue2 "$@"	
    elif [ "$INFOSYS" = "file" ]; then
        print_channel_file_glue2 "$@"
    else
        echo "ERROR: unknown information system: '$INFOSYS'" >&2
        exit 1
    fi
}



function print_channel_bdii {
CHNAME="$1"
SOURCE="$2"
DESTINATION="$3"
NAME="$4"
STATUSINFO="$5"
if [ "$STATUSINFO" = 'Active' ]; then
    STATUS='OK'
else
    STATUS='Other'
fi
cat <<EOF
dn: GlueServiceUniqueID=$CHNAME,Mds-vo-name=resource,o=grid
objectClass: GlueTop
objectClass: GlueService
objectClass: GlueSchemaVersion
objectClass: GlueKey
GlueServiceUniqueID: $CHNAME
GlueServiceName: $CHNAME
GlueServiceType: org.glite.ChannelAgent
GlueServiceVersion: $VERSION
GlueServiceEndpoint: none
GlueServiceWSDL: none
GlueServiceAccessPointURL: none
GlueServiceSemantics: normal
GlueServiceStartTime: $DATE
GlueServiceStatus: $STATUS
GlueServiceStatusInfo: $STATUSINFO
GlueForeignKey: GlueServiceUniqueID=${NAME}_org.glite.FileTransfer
GlueForeignKey: GlueServiceUniqueID=${NAME}_org.glite.ChannelManagement
GlueForeignKey: GlueServiceUniqueID=${NAME}_org.glite.Delegation
GlueSchemaVersionMajor: 1
GlueSchemaVersionMinor: 2
EOF
if [ -n "$SITE" ]; then
    echo "GlueForeignKey: GlueSiteUniqueId=$SITE"
fi
for vo in $CHVOS; do 
    echo "GlueServiceOwner: $vo"
    echo "GlueServiceAccessControlRule: $vo"
done
for vo in $VOS; do 
    echo "GlueServiceAccessControlBaseRule: VO:$vo"
done


cat <<EOF

dn: GlueServiceDataKey=source,GlueServiceUniqueID=$CHNAME,Mds-vo-name=resource,o=grid
objectClass: GlueTop
objectClass: GlueServiceData
objectClass: GlueKey
objectClass: GlueSchemaVersion
GlueServiceDataKey: source
GlueServiceDataValue: $SOURCE
GlueChunkKey: GlueServiceUniqueID=$CHNAME
GlueSchemaVersionMajor: 1
GlueSchemaVersionMinor: 2

dn: GlueServiceDataKey=destination,GlueServiceUniqueID=$CHNAME,Mds-vo-name=resource,o=grid
objectClass: GlueTop
objectClass: GlueServiceData
objectClass: GlueKey
objectClass: GlueSchemaVersion
GlueServiceDataKey: destination
GlueServiceDataValue: $DESTINATION
GlueChunkKey: GlueServiceUniqueID=$CHNAME
GlueSchemaVersionMajor: 1
GlueSchemaVersionMinor: 2

EOF
}

function print_channel_file {
CHNAME="$1"
SOURCE="$2"
DESTINATION="$3"
NAME="$4"
cat <<EOF
  <service name='$CHNAME'>
    <parameters>
      <endpoint>none</endpoint>
      <type>org.glite.ChannelAgent</type>
      <version>$VERSION</version>
      <wsdl>none</wsdl>
      <param name="source">$SOURCE</param>
      <param name="destination">$DESTINATION</param>
EOF
if [ -n "$SITE" ]; then
    echo "      <site>$SITE</site>"
fi
if [ -n "$CHVOS" ]; then
    echo '      <volist>'
    for vo in $CHVOS; do echo "        <vo>$vo</vo>"; done
    echo '      </volist>'
fi
cat <<EOF
    </parameters>
    <associatedservices>
      <name>${NAME}_org.glite.ChannelManagement</name>
      <name>${NAME}_org.glite.FileTransfer</name>
      <name>${NAME}_org.glite.Delegation</name>
    </associatedservices>
  </service>
EOF
}

##########################GLUE2 CHANNEL STUFF START######################
function print_channel_bdii_glue2 {
CHNAME="$1"
SOURCE="$2"
DESTINATION="$3"
NAME="$4"
STATUSINFO="$5"
if [ "$STATUSINFO" = 'Active' ]; then
    STATUS='OK'
else
    STATUS='Other'
fi
cat <<EOF
dn: GLUE2ShareID=$CHNAME,GLUE2GroupID=resource,o=glue
objectClass: GLUE2Share
GLUE2ShareDescription: FTS ChannelAgent $CHNAME
GLUE2ShareEndpointForeignKey: ${ENDPOINT}_org.glite.fts

EOF
}


function print_channel_file_glue2 {
CHNAME="$1"
SOURCE="$2"
DESTINATION="$3"
NAME="$4"
cat <<EOF
  <service name='$CHNAME'>
    <parameters>
      <endpoint>none</endpoint>
      <type>org.glite.ChannelAgent</type>
      <version>$VERSION</version>
      <wsdl>none</wsdl>
      <param name="source">$SOURCE</param>
      <param name="destination">$DESTINATION</param>
EOF
if [ -n "$SITE" ]; then
    echo "      <site>$SITE</site>"
fi
if [ -n "$CHVOS" ]; then
    echo '      <volist>'
    for vo in $CHVOS; do echo "        <vo>$vo</vo>"; done
    echo '      </volist>'
fi
cat <<EOF
    </parameters>
    <associatedservices>
      <name>${NAME}_org.glite.ChannelManagement</name>
      <name>${NAME}_org.glite.FileTransfer</name>
      <name>${NAME}_org.glite.Delegation</name>
    </associatedservices>
  </service>
EOF
}
##########################GLUE2 CHANNEL STUFF START END######################

#######################################################################
# system parameters
if [ -e "/var/run/tomcat5.pid" ]; then
    DATE=$(stat -c %z /var/run/tomcat5.pid)
    DATE_GLUE2=$(stat -c %z /var/run/tomcat5.pid | sed -e  's/ /T/g'  -e 's/.000000000T/Z/g')
    SERVICE_STATUS='OK'
    SERVICE_STATUS_GLUE2='ok'
else
    # Using a fixed date to avoid frequent BDII updates
    DATE='1970-01-01T00:00:00Z'
    DATE_GLUE2='1970-01-01T00:00:00Z'
    SERVICE_STATUS='Unknown'
fi
VERSION=$(rpm -q --qf '%{VERSION}' glite-data-transfer-fts)


#GLUE2 looping over HOSTALIASES
for HOSTALIAS in $HOSTALIASES; do

    #######################################################################
    # tomcat parameters
    
    [ "$VERBOSE" = 'true' ] && echo "INFO: Parsing '$TOMCAT_CONF/server.xml'" >&2
    BASEURL=$(xsltproc --stringparam HOSTNAME $HOSTALIAS $TOMCAT_XSLT $TOMCAT_CONF/server.xml)
    [ "$VERBOSE" = 'true' ] && echo "INFO: BASEURL='$BASEURL'" >&2
    
    #######################################################################
    # scanning for services
    
    print_start
    for context in $(find $TOMCAT_CONF -follow -name 'glite-data-transfer-fts*.xml'); do
        [ "$VERBOSE" = 'true' ] && echo "INFO: Parsing '$context'" >&2
        ENDPOINT=${BASEURL}/$(basename $context .xml | sed -e 's,#,/,g')
        [ "$VERBOSE" = 'true' ] && echo "INFO: ENDPOINT='$ENDPOINT'" >&2
        NAME=$(basename "$context" .xml | sed -e 's/#/_/g;')"_"$HOSTALIAS
    
        if [ "$PUBLISH_CHANNELS" = 'true' ]; then
            if [ ! -r ${DBPARAMFILE} ]; then
               echo "ERROR: cannot read DB parameter file"
               exit 1
            fi 
            source ${DBPARAMFILE}
    	    tmpfile=`mktemp`
            sqlplus -S ${DBUSER}/${DBPASS}@"${DBCONN}" < ${CHANNELSQL} > ${tmpfile} 
            if [ $? -ne 0 ]; then
                echo "ERROR: cannot connect to the database." >&2
                exit 3
            fi
            while read channel state SOURCE DESTINATION CHVOS; do
                [ "$VERBOSE" = 'true' ] && echo "INFO: Inspecting '$channel'" >&2
                [ "$VERBOSE" = 'true' ] && echo "INFO: from '$SOURCE' to '$DESTINATION'" >&2
                VOS="$VOS $CHVOS"
                print_channel "${channel}_${HOSTALIAS}_org.glite.ChannelAgent" "$SOURCE" "$DESTINATION" "$NAME" "$state"
            done <${tmpfile}
            rm -f ${tmpfile}
        fi
    
        # removing duplicates from the VO bag
        VOS=$(echo "$VOS" | sed -e 's/[[:space:]]/\n/g' | sort -u)
        print_service "$NAME" "$ENDPOINT"
    done
    print_end
done




#GLUE2 looping over HOSTALIASES
for HOSTALIAS in $HOSTALIASES; do

    #######################################################################
    # tomcat parameters
    
    [ "$VERBOSE" = 'true' ] && echo "INFO: Parsing '$TOMCAT_CONF/server.xml'" >&2
    BASEURL=$(xsltproc --stringparam HOSTNAME $HOSTALIAS $TOMCAT_XSLT $TOMCAT_CONF/server.xml)
    [ "$VERBOSE" = 'true' ] && echo "INFO: BASEURL='$BASEURL'" >&2
    
    #######################################################################
    # scanning for services
    
    print_start
    for context in $(find $TOMCAT_CONF -follow -name 'glite-data-transfer-fts*.xml'); do
        [ "$VERBOSE" = 'true' ] && echo "INFO: Parsing '$context'" >&2
        ENDPOINT=${BASEURL}/$(basename $context .xml | sed -e 's,#,/,g')
        [ "$VERBOSE" = 'true' ] && echo "INFO: ENDPOINT='$ENDPOINT'" >&2
        NAME=$(basename "$context" .xml | sed -e 's/#/_/g;')"_"$HOSTALIAS
    
        if [ "$PUBLISH_CHANNELS" = 'true' ]; then
            if [ ! -r ${DBPARAMFILE} ]; then
               echo "ERROR: cannot read DB parameter file"
               exit 1
            fi 
            source ${DBPARAMFILE}
    	    tmpfile=`mktemp`
            sqlplus -S ${DBUSER}/${DBPASS}@"${DBCONN}" < ${CHANNELSQL} > ${tmpfile} 
            if [ $? -ne 0 ]; then
                echo "ERROR: cannot connect to the database." >&2
                exit 3
            fi
            while read channel state SOURCE DESTINATION CHVOS; do
                [ "$VERBOSE" = 'true' ] && echo "INFO: Inspecting '$channel'" >&2
                [ "$VERBOSE" = 'true' ] && echo "INFO: from '$SOURCE' to '$DESTINATION'" >&2
                VOS="$VOS $CHVOS"
                print_channel_glue2 "${channel}_${HOSTALIAS}_org.glite.ChannelAgent" "$SOURCE" "$DESTINATION" "$NAME" "$state"
            done <${tmpfile}
            rm -f ${tmpfile}
        fi
    
        # removing duplicates from the VO bag
        VOS=$(echo "$VOS" | sed -e 's/[[:space:]]/\n/g' | sort -u)
        print_service_glue2 "$NAME" "$ENDPOINT"
    done
    print_end
done
