#!/bin/bash

# This script allows to upload a single to an WebDav endpoint

webdav="$1"
credential="$2"
localfile="$3"
remotefile="$4"

function CreateRemoteDir () {
    local dir="$1"
    local status="$(curl -X GET -u "$credential" "$webdav/$dir/" -L --silent --output /dev/null --write-out "%{http_code}")"

    if [[ "$status" == "404" ]]; then
        local next="$(dirname $dir)"
        if [[ "$dir" == "." ]]; then
            echo "Root folder not found" > /dev/fd/2
            exit 1
        fi

        CreateRemoteDir "$next"
        echo -n "Create $dir: "
        curl -X MKCOL -u "$credential" "$webdav/$dir/" -L --silent | grep title
        echo ""
    fi
}

CreateRemoteDir "$(dirname $remotefile)"

curl -X PUT --data-binary "@$localfile" -u "$credential" "$webdav/$remotefile" -L
