#
if [ -z "$CONF_FILE" ]
then
    CONF_FILE=.setenv
fi
if [ ! -f "$CONF_FILE" ]
then
    echo "No configuration defined. Create a file named '.setenv' or set env. variable CONF_FILE"
    exit
fi
. $CONF_FILE

BASEURL="${NUXEO_PROTOCOL:-http}://${NUXEO_SERVER}${APP_URL:-/nuxeo}"
WS_ROOT_PATH="/default-domain/workspaces"
WS_DOCNAME="NXP"
PARENT_PATH="${WS_ROOT_PATH}/${WS_DOCNAME}"
NXQL="SELECT * FROM Document WHERE ecm:path STARTSWITH '${PARENT_PATH}' AND ecm:isTrashed=0 AND ecm:isVersion=0 AND ecm:isProxy=0"
NBR=200

function getOrCreateWorkspaceId {
    local __parentPath=$1
    local __docName=$2
    curl -sfu $NUXEO_USER:$NUXEO_PASSWORD -o /dev/null -r0-0 ${BASEURL}/api/v1/path${__parentPath}/${__docName}
    if [ $? -ne 0 ]
    then
        curl -su $NUXEO_USER:$NUXEO_PASSWORD -XPOST -H 'Content-Type:application/json' \
${BASEURL}/api/v1/path${__parentPath} \
-d '{
  "entity-type": "document",
  "name": "'${__docName}'",
  "type": "Workspace",
  "properties": {
    "dc:title": "'${__docName}'"
  }
}' \
| jq -r '.uid'
        WS_CREATED="true"
    else
        curl -su $NUXEO_USER:$NUXEO_PASSWORD -H 'Content-Type:application/json' \
${BASEURL}/api/v1/path${__parentPath}/${__docName} \
| jq -r '.uid'
    fi
}

function getOrCreateCollection {
    local __collName=$1
    local __collId=$(curl -su $NUXEO_USER:$NUXEO_PASSWORD -XPOST -H'Content-Type:application/json' \
${BASEURL}/api/v1/automation/User.GetCollections \
-d '{ "params": { "searchTerm":"'${__collName}'" }}' \
| jq -r '.entries[0].uid')
    if [ ${__collId} == "null" ]
    then
        curl -su $NUXEO_USER:$NUXEO_PASSWORD -XPOST -H'Content-Type:application/json' \
${BASEURL}/api/v1/automation/Collection.Create \
-d '{ "params": { "name":"'${__collName}'" }}' \
| jq -r '.uid'
    fi
    echo "${__collId}"  
}

function addToCollectionId {
    local __collDocId=$1
    echo "* Collection UUID: ${__collDocId}"
    local __ENCODED_NXQL=$(python -c "import urllib, sys; print urllib.quote(sys.argv[1])" "$NXQL")
    echo "* Encoded NXQL: $__ENCODED_NXQL"
    curl -su $NUXEO_USER:$NUXEO_PASSWORD -X POST -H 'Content-Type: application/json' \
${BASEURL}/api/v1/search/bulk/automation?query=${__ENCODED_NXQL} \
-d '{
  "operationId": "Document.AddToCollection",
  "parameters": {
    "collection": "'${__collDocId}'"
  }
}' | wait_for_bulk_action_completion.sh -
}

## Ensure workspace exists

WS_CREATED=""
WS_ID=$(getOrCreateWorkspaceId ${WS_ROOT_PATH} ${WS_DOCNAME})
echo "* ${PARENT_PATH}: ${WS_ID}"
[ "${WS_ID}" == "null" ] && exit 2;

## bulk create documents
bulk_create_documents.sh ${PARENT_PATH} ${NBR}

## Add document to collections

## Get collection ID and create if non-existent
COLL="${WS_DOCNAME}_coll1"
echo "* Collection: ${COLL}"
COLL_ID=$(getOrCreateCollection ${COLL})

## Add created documents to a collection
addToCollectionId ${COLL_ID}

read -p "Delete created documents and workspace? (Y/n) " -n 1 -r REPLY
REPLY=${REPLY:-Y}
REPLY=${REPLY^}
[ $REPLY == "Y" ] && curl -su $NUXEO_USER:$NUXEO_PASSWORD -X POST \
-H'Content-Type: application/json' \
${BASEURL}/api/v1/id/${WS_ID}/@op/Document.Delete \
-d '{ "context": {} }' |jq

