# Requirements:
# - `jq` command
#
# This script creates documents

USAGE="Usage: $0 <folder_document_path> <end_index>\n  $0 <folder_document_path> <start_index> <end_index> [ <document_type ]\n  Ex: $0 /default-domain/workspaces/ws1 50\n  Ex: $0 /default-domain/workspaces/ws1 10 19 File"
if [ $# -lt 1 ]
then
    echo "Missing paramters."
    echo -e $USAGE
    exit
fi
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
#cat $CONF_FILE

source utils.sh

DOCUMENT_PARENT_PATH=$(urlEncode "$1")
START_IDX=0
END_IDX=$2
if [ $# -ge 3 ]
then
    START_IDX=$2
    END_IDX=`expr $3+1`
fi
DOCTYPE=File
if [ $# -gt 3 ]
then
    DOCTYPE=$4
fi

BASEURL=http://localhost:8080/nuxeo
FILEDOC=${DOCTYPE}
URL="${NUXEO_PROTOCOL:-http}://$NUXEO_SERVER${APP_URL:-/nuxeo}/api/v1/path${DOCUMENT_PARENT_PATH}"

# Administrator creates documents in workspace

val=$(( $END_IDX - 1 ))
digit_nbr=`echo -n "${val}" | wc -c`
format_str="%0${digit_nbr}d"

for ((i=$START_IDX; i<$END_IDX; i++))
do
    printf -v idx "$format_str" $i
    docname=${FILEDOC}_${idx}
    JSON=$(curl -XPOST -su $NUXEO_USER:$NUXEO_PASSWORD \
    -H'content-type: application/json' -H'properties:*' -H'Repository:${NUXEO_REPOSITORY:-default}'\
    ${URL} \
    -d"{
      \"entity-type\": \"document\",
      \"type\": \"File\",
      \"name\": \"${docname}\",
      \"properties\": {
        \"dc:title\": \"${docname}\"
      }
    }")
    #echo $JSON | jq
    FILEPATH=$(echo $JSON | jq -r '.path')
    echo "${FILEPATH} created."
done

echo "Done."
