#!/bin/bash
# Common functions to interact with a WebDAV endpoint

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

DAVLIB_LOG="/tmp/davlib.out"

# Create directory
function MKCOL() {
  HTTP_CODE=`curl -s -o "${DAVLIB_LOG}" -w "%{http_code}\\n" -L -E ${X509_USER_PROXY} --cacert ${X509_USER_PROXY} --CApath ${X509_CERT_DIR} -X MKCOL "https://${DPM_HOST}/$1" | tr -d "[:space:]"`
  echo -e "[$HTTP_CODE:MKCOL]    $1"
}

# Remove something
function DELETE() {
  HTTP_CODE=`curl -s -o "${DAVLIB_LOG}" -w "%{http_code}\\n" -L -E ${X509_USER_PROXY} --cacert ${X509_USER_PROXY} --CApath ${X509_CERT_DIR} -X DELETE "https://${DPM_HOST}/$1" | tr -d "[:space:]"`
  echo -e "[$HTTP_CODE:DELETE]   $1"
}

# Put a file
function PUT() {
  HTTP_CODE=`curl -s -o "${DAVLIB_LOG}" -w "%{http_code}\\n" -L -E ${X509_USER_PROXY} --cacert ${X509_USER_PROXY} --CApath ${X509_CERT_DIR} -T "$1" "https://${DPM_HOST}/$2" | tr -d "[:space:]"`
  echo -e "[$HTTP_CODE:UPLOAD]   $1 to $2"
}

# Get a file
function GET() {
  HTTP_CODE=`curl -s -o "$2" -w "%{http_code}\\n" -L -E ${X509_USER_PROXY} --cacert ${X509_USER_PROXY} --CApath ${X509_CERT_DIR} "https://${DPM_HOST}/$1" | tr -d "[:space:]"`
  echo -e "[$HTTP_CODE:DOWNLOAD] $1 to $2"
}

# Get checksum from the header
# $2 is the type (i.e. md5)
function DIGEST() {
  DIGEST_VALUE=`curl -s -I -L -E ${X509_USER_PROXY} --cacert ${X509_USER_PROXY} --CApath ${X509_CERT_DIR} "https://${DPM_HOST}/$1" -H "Want-Digest: $2" |  grep "Digest: " | sed -E "s/Digest: $2=(\w+)\r/\1/"`
  if [ $? -eq 0 ]; then
	echo  "[CHECKSUM] Got the digest value $2='$DIGEST_VALUE'"
  else
    DIGEST_VALUE=""
    echo  "[CHECKSUM] Could not get the digest type $2 for $1"
  fi
}

# Get a given DAV property
# $2 is the property (i.e. LCGDM::checksum.md5)
function PROPERTY() {
  RAW=`curl -s -E ${X509_USER_PROXY} --cacert ${X509_USER_PROXY} --CApath ${X509_CERT_DIR} "https://${DPM_HOST}/$1" -X "PROPFIND"`
  VALUE=`echo "$RAW" | xpath -q -e "/D:multistatus/D:response/D:propstat/D:prop/lp3:$2/text()"`
}

