#!/bin/bash

#  Copyright (c) 2016, Oracle and/or its affiliates.  All rights reserved.
#  
#  This software is dual-licensed to you under the MIT License (MIT) and
#  the Universal Permissive License (UPL).  See the LICENSE file in the root
#  directory for license terms.  You may choose either license, or both.
#  

if [[ "$1" == '--help' || "$1" == '-h' ]]
   then
   echo "retrieve-messages usage: ./retrieve-messages ENDPOINT_ID IOT_USERNAME IOT_PASSWORD IOTSERVER PORT"
   exit 0
fi

if [ -f ../json/device.json ]; then
	export ENDPOINT_ID=$(grep -oE '"id"\s*\:\s*\"[^"]+"' ../json/device.json | grep -oE '[^"]+"$' | grep -oE '[^"]+')
fi

echo "============================================================================================"
echo "Step 9: Rereieving messages from $ENDPOINT_ID: "
if [ -n "$ENDPOINT_ID" ] && [ -n "$IOT_USERNAME" ] && [ -n "$IOT_PASSWORD" ] && [ -n "$IOTSERVER" ] && [ -n "$PORT" ]; then
	echo "cURL command: "
	echo -e "curl -H \"Accept:application/json\" -u \"$IOT_USERNAME:$IOT_PASSWORD\" \"$IOTSERVER:$PORT/iot/api/v2/messages?device=$ENDPOINT_ID\""
	echo -e "\nResponse: "
	curl -H "Accept:application/json" -u "$IOT_USERNAME:$IOT_PASSWORD" "$IOTSERVER:$PORT/iot/api/v2/messages?device=$ENDPOINT_ID"
elif [ $# -eq 5 ]; then
	echo "cURL command: "
	echo -e "curl -H \"Accept:application/json\" -u \"$2:$3\" \"$4:$5/iot/api/v2/messages?device=$1\""
	echo -e "\nResponse: "
	curl -H "Accept:application/json" -u "$2:$3" "$4:$5/iot/api/v2/messages?device=$1"
else
	echo "retrieve-messages usage: ./retrieve-messages ENDPOINT_ID IOT_USERNAME IOT_PASSWORD IOTSERVER PORT"
   	exit 1
fi
echo