#!/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 "generate-token-send-messages usage: ./generate-token-send-messages ENDPOINT_ID FORMAT_URN IOTSERVER PORT"
	exit 0
fi

# We are determine the ENDPOINT_ID here when you run this script seperately
if [ -f ../json/device.json ]; then
	export ENDPOINT_ID=$(grep -oE '"id"\s*\:\s*\"[^"]+"' ../json/device.json | grep -oE '[^"]+"$' | grep -oE '[^"]+')
fi

if [ -n "$ENDPOINT_ID" ] && [ -n "$FORMAT_URN" ] && [ -n "$IOTSERVER" ] && [ -n "$PORT" ]; then
	# Get message token
	./get-message-token

	echo "============================================================================================"
	export MESSAGE_TOKEN=$(grep -A0 '"access_token":' ../json/message_token.json | grep -o "[A-Z0-9a-z]\{32\}")
	echo "Message access token: $MESSAGE_TOKEN"

	# Send messages from certain device
	read -rsp $'Press any key to continue...\n' -n1 key
	./send-messages
elif [ $# -eq 4 ]; then
	# Get message token
	read -rsp $'Press any key to continue...\n' -n1 key
	./get-message-token $1 $3 $4

	echo "============================================================================================"
	export MESSAGE_TOKEN=$(grep -A0 '"access_token":' ../json/message_token.json | grep -o "[A-Z0-9a-z]\{32\}")
	echo "Message access token: $MESSAGE_TOKEN"

	# Send messages from certain device
	read -rsp $'Press any key to continue...\n' -n1 key
	./send-messages $1 $2 $MESSAGE_TOKEN $3 $4
else 
	echo "generate-token-send-messages usage: ./generate-token-send-messages ENDPOINT_ID FORMAT_URN IOTSERVER PORT"
	exit 1
fi	
echo