#!/bin/bash
# meta: proxy=True
# meta: preconfig=../../DPM-config
##############################################################################
# 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: Dimitar Shiyachki <Dimitar.Shiyachki@cern.ch>
#
##############################################################################

SCRIPTDIR="$(dirname "$(readlink -f ${BASH_SOURCE})")"
source "${SCRIPTDIR}/../../Macros"

PROXY_NEEDED

TEST_DIR=d`date +%s%N`
TEST_SUBDIR1=s1`date +%s%N`
TEST_SUBDIR2=s2`date +%s%N`
TEMP_FILE=/tmp/_dpm_test_temp`date +%s%N`

cleanup ()
{
   dpns-rm $TEST_DIR/$TEST_SUBDIR1/link_1
   lcg-del --nolfc -v -b -D srmv2 srm://$DPM_HOST:$SRMV2_PORT/srm/managerv2\?SFN=/$DPNS_HOME/$TEST_DIR/bash_copy_1
   dpns-rm -r $TEST_DIR
   rm -f $TEMP_FILE
}

echo "Creating directory $TEST_DIR/$TEST_SUBDIR1/$TEST_SUBDIR2"
dpns-mkdir -p $TEST_DIR/$TEST_SUBDIR1

echo "Copying a file in $TEST_DIR/$TEST_SUBDIR1"
lcg-cp -v -b -D srmv2 file:/bin/bash srm://$DPM_HOST:$SRMV2_PORT/srm/managerv2\?SFN=/$DPNS_HOME/$TEST_DIR/bash_copy_1

echo "Creating a symbolic link to bash_copy_1 in $TEST_DIR/$TEST_SUBDIR1"
dpns-ln -s $DPNS_HOME/$TEST_DIR/bash_copy_1 $TEST_DIR/$TEST_SUBDIR1/link_1
ret=$?
if [ $ret -ne 0 ]; then
   cleanup
   TEST_FAILED "dpns-ln exited with code $ret. Test has failed."
fi

echo "Link created successfully. Trying to copy the file locally via the link."
lcg-cp -v -b -D srmv2 srm://$DPM_HOST:$SRMV2_PORT/srm/managerv2\?SFN=/$DPNS_HOME/$TEST_DIR/$TEST_SUBDIR1/link_1 $TEMP_FILE
if [ $? -ne 0 ]; then
   cleanup
   TEST_FAILED "Cannot read the file by using the symbolic link. Test has failed."
else
   echo -n "Comparing the original with the file read"
   cmp /bin/bash $TEMP_FILE
   if [ $? -ne 0 ]; then
      cleanup 
      TEST_FAILED "Files are not the same"
   fi
fi

cleanup

echo
echo "OVERALL RESULT:"
TEST_PASSED

