USAGE="Usage: $0 <commandId> [ [<curl_credentials>] [base_Nuxeo_url] ]\n"
if [ $# -lt 1 ]
then
    echo "Missing paramters."
    echo -e $USAGE
    exit
fi

COMMAND_ID=$1
if [ "$COMMAND_ID" = "-" ]
then
    # Read stdin
    #jq <&0
    BULK_JSON=$(</dev/stdin)
    COMMAND_ID=$(echo $BULK_JSON |jq -r '.commandId')
    echo $BULK_JSON |jq
    #echo "here $COMMAND_ID"
fi
NUXEO_CRED="Administrator:Administrator"
if [ $# -gt 1 ]
then
    NUXEO_CRED=$2
fi
NUXEO_PORT=${NUXEO_PORT:-8080}
NUXEO_PORT=":$NUXEO_PORT"
NUXEO_HOST=${NUXEO_HOST:-localhost}

if [ "$NUXEO_CRED" = "-" ]
then
    NUXEO_CRED_PARAM="-ns"
else
    NUXEO_CRED_PARAM="-u $NUXEO_CRED"
fi
NUXEO_SERVER=$NUXEO_HOST$NUXEO_PORT
BASE_URL="${NUXEO_PROTOCOL:-http}://$NUXEO_SERVER${APP_URL:-/nuxeo}"
if [ $# -gt 2 ]
then
    BASE_URL=$3
fi

## Check connection to Nuxeo server

NUXEO_STATUS=`curl -Isw "%{http_code}\n" -o /dev/null ${BASE_URL}/login.jsp`
if [ "${NUXEO_STATUS}" != "200" ]
then
    echo "! Connection to ${BASE_URL} failed (${NUXEO_STATUS})."
    exit 1
fi

STATUS_JSON="N/A"
ACTION_STATE="RUNNING"
while [ "$ACTION_STATE" != "COMPLETED" -a "$ACTION_STATE" != "ABORTED" ]
do
    sleep 1
    STATUS_JSON=`curl -s $NUXEO_CRED_PARAM \
    -H 'content-type: application/json' \
    ${BASE_URL}/api/v1/bulk/${COMMAND_ID}`
    #echo "${STATUS_JSON}"|jq
    ENTITY_TYPE=`echo "${STATUS_JSON}"|jq -r '.["entity-type"]'`
    if [ "$ENTITY_TYPE" = "exception" ]
    then
        echo "${STATUS_JSON}"|jq -r '.message'
        exit 1
    fi
    ACTION_STATE=`echo "${STATUS_JSON}"|jq -r '.state'`
    ACTION_MSG=`echo "${STATUS_JSON}"|jq -jr '.processed," / ",.total," / ",.errorCount'`
    echo "* State: $ACTION_STATE ${ACTION_MSG}"
done
echo "${STATUS_JSON}"|jq

