#!/bin/sh

##############################################################################
# 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.
##############################################################################

BDII_CONF=${1:-/etc/bdii/bdii.conf}

if [ -f "$BDII_CONF" ]; then
    . "$BDII_CONF"
else
    echo "Configuration file $BDII_CONF not found ..."
    exit 1
fi

egrep '^BDII_PROXY= *$' $BDII_CONF > /dev/null && exit 0

f=$BDII_DIR/etc/bdii/proxy.conf

if test -f $f
then
    egrep '^BDII_PROXY= *$' $f > /dev/null && exit 0
    . $f
fi

proxy=${BDII_PROXY:-$BDII_VAR_DIR/hostproxy}
proxy_file=$proxy.$$

mkdir -p `dirname $proxy_file`

cert=${X509_HOST_CERT:-/etc/grid-security/hostcert.pem}
key=${X509_HOST_KEY:-/etc/grid-security/hostkey.pem}

test -f "$cert" && test -f "$key" || exit 0

id -u "$BDII_USER" > /dev/null || exit 1

#Try setting GLOBUS_LOCATION
if [ "x$GLOBUS_LOCATION" = "x" ]; then
    f=/etc/sysconfig/globus
    test -f $f && . $f
    : ${GLOBUS_LOCATION:=/opt/globus}
    if [ -d $GLOBUS_LOCATION ]; then
	export GLOBUS_LOCATION
    else
	unset GLOBUS_LOCATION
    fi
fi

if [ "x$GLOBUS_LOCATION" = "x" ]; then
    test -f /usr/bin/grid-proxy-init || exit 0
    /usr/bin/grid-proxy-init -q -cert $cert -key $key -out $proxy_file
else
    f=$GLOBUS_LOCATION/etc/globus-user-env.sh
    test -f $f || exit 0
    . $f
    $GLOBUS_LOCATION/bin/grid-proxy-init -q -cert $cert -key $key -out $proxy_file
fi

chown $BDII_USER $proxy_file
mv -f $proxy_file $proxy
