#!/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.
#  

#Run getToken.jar to get access_token
if [[ "$1" == '--help' || "$1" == '-h' ]]
	then
	echo "activate usage: ./activate SHARED_SECRET ACTIVATION_ID 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

# Get activation token
if [ -n "$SHARED_SECRET" ] && [ -n "$ACTIVATION_ID" ] && [ -n "URN" ] && [ -n "$IOTSERVER" ] && [ -n "$PORT" ]; then
	./get-activation-token

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

	# Get activation policy
	read -rsp $'Press any key to continue...\n' -n1 key
	./get-activation-policy

	# Generate RSA key pair
	read -rsp $'Press any key to continue...\n' -n1 key
	./generate-RSA

	# Generate activation payload and directly activate device with certain device id (endpointId)
	read -rsp $'Press any key to continue...\n' -n1 key
	./direct-activation
elif [ $# -eq 5 ]; then
	read -rsp $'Press any key to continue...\n' -n1 key
	./get-activation-token $1 $2 $4 $5

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

	# Get activation policy
	read -rsp $'Press any key to continue...\n' -n1 key
	./get-activation-policy $ACCESS_TOKEN $2 $4 $5

	# Generate RSA key pair
	read -rsp $'Press any key to continue...\n' -n1 key
	./generate-RSA

	# Generate activation payload and directly activate device with certain device id (endpointId)
	read -rsp $'Press any key to continue...\n' -n1 key
	./direct-activation $2 $1 $3 $ACCESS_TOKEN $4 $5
else
	echo "activate usage: ./activate SHARED_SECRET ACTIVATION_ID URN IOTSERVER PORT"
	exit 1
fi
echo




