#!/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: David Smith <David.Smith@cern.ch>
#
##############################################################################

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

PROXY_NEEDED

TEST_FILE=xrd-f`date +%s%N`
TEMP_FILE=/tmp/_xrootd_test_temp

echo
echo "Target url will be: root://$DPM_HOST//$VO/$TEST_FILE"
echo

echo "Restarting dpm daemon (workaround to make sure it has read latest /etc/shift.conf)"
DPM_HOST_EXEC "/sbin/service dpm restart"
ret=$?
if [ $ret -ne 0 ]; then
   TEST_FAILED "service dpm restart exited with code $ret"
fi

dd if=/dev/urandom of=$TEMP_FILE bs=1000 count=150000 >& /dev/null

echo -n "Copying 150MB test file to storage"
sync
echo 3 > /proc/sys/vm/drop_caches
xrdcp $TEMP_FILE root://$DPM_HOST//$VO/$TEST_FILE
if [ $? -eq 0 ]; then
   echo "...ok"
else
   echo "...fail"
   rm -f $TEMP_FILE
   TEST_FAILED "Failure when running xrdcp to copy the file to the storage"
fi

echo -n "Copying test file back from the storage"
sync
echo 3 > /proc/sys/vm/drop_caches
xrdcp root://$DPM_HOST//$VO/$TEST_FILE ${TEMP_FILE}.out
if [ $? -eq 0 ]; then
   echo "...ok"
else
   echo "...fail"
   rm -f $TEMP_FILE ${TEMP_FILE}.out
   xrd $DPM_HOST rm /$VO/$TEST_FILE >& /dev/null
   TEST_FAILED "Failure when running xrdcp to copy the file back"
fi

echo -n "Comparing file sent and retrieved"

cmp -s $TEMP_FILE ${TEMP_FILE}.out
if [ $? -eq 0 ]; then
   echo "...ok"
else
   echo "...fail"
   rm -f $TEMP_FILE ${TEMP_FILE}.out
   xrd $DPM_HOST rm /$VO/$TEST_FILE >& /dev/null
   TEST_FAILED "Failure to confirm the files are identical"
fi

rm $TEMP_FILE ${TEMP_FILE}.out
xrd $DPM_HOST rm /$VO/$TEST_FILE

echo -n "Confirming that the test file was removed from the storage"
xrdcp -f root://$DPM_HOST//$VO/$TEST_FILE /dev/null >& /dev/null
if [ $? -eq 0 ]; then
   echo "...fail"
   TEST_FAILED "Copy succeeded even though the file should have been removed"
else
   echo "...ok"
fi

echo
echo "OVERALL RESULT:"
TEST_PASSED
