#!/bin/bash
# Upload a file to a space token
# meta: proxy=true
# meta: preconfig=../../DPM-config

source davlib

SPACE_TOKEN="dav-reserved"
REMOTE="${DPNS_HOME}/reserved.`date +%s`"
LOCAL="/tmp/dav-reserved.tmp"

# Function to return the free space of a space token
function get_free_space() {
  OUT=`dpm-getspacemd --token_desc $1 | tail -n 1 | cut -f 2`
  FREE=`echo $OUT | cut -d ' ' -f 2`

  # Suffix processing
  SUFFIX=${FREE:${#FREE}-1:1}
  VALUE=${FREE:0:${#FREE}-1}
  VALUE=`echo $VALUE | cut -d '.' -f 1`

  if [ $SUFFIX == "T" ] || [ $SUFFIX == "t" ]; then
    FREE=$((VALUE * 1024 * 1024 * 1024 * 1024))
  elif [ $SUFFIX == "G" ] || [ $SUFFIX == "g" ]; then
    FREE=$((VALUE * 1024 * 1024 * 1024))
  elif [ $SUFFIX == "M" ] || [ $SUFFIX == "m" ]; then
    FREE=$((VALUE * 1024 * 1024))
  elif [ $SUFFIX == "K" ] || [ $SUFFIX == "k" ]; then
    FREE=$((VALUE * 1024))
  fi
}

# Create the space token
SPACE_ID=`dpm-reservespace --gspace 200M --token_desc "${SPACE_TOKEN}"`
if [ $? -ne 0 ]; then
  TEST_FAILED "Could not reserve space"
fi

# Confirm reservation
get_free_space "${SPACE_TOKEN}"
echo "Space reserved with $FREE bytes"
PREV_FREE=$FREE

# Create the file 
dd if=/dev/zero of=${LOCAL} bs=1M count=100 &> /dev/null
echo "100M file created"

# Upload the file
PUT "${LOCAL}" "${REMOTE}?spacetoken=${SPACE_TOKEN}"
if [ $HTTP_CODE -lt 200 ] || [ $HTTP_CODE -gt 299 ]; then
  dpm-releasespace --token_desc "${SPACE_TOKEN}" --force
  TEST_FAILED "Could not put the file"
fi

# Check the free space
get_free_space "${SPACE_TOKEN}"
if [ $PREV_FREE -le $FREE ]; then
  dpm-releasespace --token_desc "${SPACE_TOKEN}" --force
  TEST_FAILED "The file didn't go to the requested space token!"
fi
echo "Current free space: $FREE < $PREV_FREE"

# Try again, but now it must fail (not enough space)
PUT "${LOCAL}" "${REMOTE}.2?spacetoken=${SPACE_TOKEN}"
get_free_space "${SPACE_TOKEN}"
echo "Current free space: $FREE < $PREV_FREE"
if [ $HTTP_CODE -eq 403 ]; then
  echo "WARNING: Got a 403. Probably mod_dav is loaded instead of mod_lcgdm_dav"
elif [ $HTTP_CODE -ne 507 ]; then
  DELETE "${REMOTE}"
  DELETE "${REMOTE}.2"
  dpm-releasespace --token_desc "${SPACE_TOKEN}" --force
  TEST_FAILED "Second attemp must fail with 507!!"
else
  echo "Second attemp failed with 'Space unavailable' (507) as expected"
fi

# Remove the file
DELETE "${REMOTE}"
DELETE "${REMOTE}.2"

# Remove the space token
dpm-releasespace --token_desc "${SPACE_TOKEN}" --force
if [ $? -ne 0 ]; then
  TEST_FAILED "Could not release space"
fi
echo "Space released"

# Now it should fail with 400
PUT "${LOCAL}" "${REMOTE}?spacetoken=${SPACE_TOKEN}"
if [ $HTTP_CODE -eq 403 ]; then
  echo "WARNING: Got a 403. Probably mod_dav is loaded instead of mod_lcgdm_dav"
elif [ $HTTP_CODE -ne 400 ]; then
  TEST_FAILED "Third attemp must fail with 400!!"
else
  echo "Third attemp failed with 'Bad request' (400) as expected"
fi

# Remove local
rm "${LOCAL}"

# Success!
TEST_PASSED

