#!/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 ()
{
   lcg-del --nolfc -v -b -D srmv2 srm://$DPM_HOST:$SRMV2_PORT/srm/managerv2\?SFN=/$DPNS_HOME/$TEST_DIR/bash_copy_1
   lcg-del --nolfc -v -b -D srmv2 srm://$DPM_HOST:$SRMV2_PORT/srm/managerv2\?SFN=/$DPNS_HOME/$TEST_DIR/$TEST_SUBDIR2/bash_copy_2
   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/$TEST_SUBDIR2

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 "Copying a file in $TEST_DIR/$TEST_SUBDIR1/$TEST_SUBDIR2"
lcg-cp -v -b -D srmv2 file:/bin/bash srm://$DPM_HOST:$SRMV2_PORT/srm/managerv2\?SFN=/$DPNS_HOME/$TEST_DIR/$TEST_SUBDIR2/bash_copy_2

echo "Trying to remove recursively $DPNS_HOME/$TEST_DIR"
echo "This should not be possible because regular files exist."
dpns-rm -r $DPNS_HOME/$TEST_DIR >$TEMP_FILE 2>&1
ret=$?
if [ $ret -eq 0 ]; then
   cleanup
   TEST_FAILED "Error. dpns-rm exited with code 0. Test has failed"
fi

if ( grep "$TEST_DIR/bash_copy_1" $TEMP_FILE | grep -q "File exists"; ) && \
      ( grep "$TEST_DIR/$TEST_SUBDIR2/bash_copy_2" $TEMP_FILE | \
           grep -q "File exists"; ); then
   echo "\"File exists\" warnings printed ok"
else
   cleanup
   TEST_FAILED "No \"File exists\" warning printed. Test has failed"
fi

cleanup

echo
echo "OVERALL RESULT:"
TEST_PASSED

