#!/bin/sh
# SPDX-License-Identifier: MIT

error() {
	printf "%s\n" "$@" >&2
	logger -t armadillo-twin-agent "$@"
	exit 1
}

set --

# Check that the required parameters are set in the environment variables
#
[ -z "$CREDENTIAL_PROVIDER_URL" ] \
	&& error "environment variable CREDENTIAL_PROVIDER_URL is not set"
[ -z "$IOT_JOB_ENDPOINT" ] \
	&& error "environment variable IOT_JOB_ENDPOINT is not set"
[ -z "$SWUPDATE_ARMADILLO_TWIN" ] \
	&& error "environment variable SWUPDATE_ARMADILLO_TWIN is not set"

# invoke the IoT Core credential provider REST API
#
ex_sss_boot_sss_port="$(device-info --se-param)"
export EX_SSS_BOOT_SSS_PORT="$ex_sss_boot_sss_port"

sn="$(device-info -s)"
set -- "$@" -sS
set -- "$@" --cert "/var/log/armadillo-twin-agent/device_cert.pem"
set -- "$@" --key "/var/log/armadillo-twin-agent/refkey.pem"
set -- "$@" --cacert "/usr/share/armadillo-twin-agent/AmazonRootCA1.pem"
set -- "$@" -H "x-amzn-iot-thingname: $sn"
set -- "$@" "https://$CREDENTIAL_PROVIDER_URL"
response="$(OPENSSL_CONF=/etc/plug-and-trust/openssl11_sss_se050.cnf curl "$@")"
# curl output example:
# ssse-flw: EmbSe_Init(): Entry
# App   :INFO :Using PortName='/dev/i2c-2:0x48' (ENV: EX_SSS_BOOT_SSS_PORT=/dev/i2c-2:0x48)
# sss   :INFO :atr (Len=35)
#       00 A0 00 00    03 96 04 03    E8 00 FE 02    0B 03 E8 08 
#       01 00 00 00    00 64 00 00    0A 4A 43 4F    50 34 20 41 
#       54 50 4F 
# sss   :WARN :Communication channel is Plain.
# sss   :WARN :!!!Not recommended for production use.!!!
# ssse-flw: Version: 1.0.5
# ssse-flw: EmbSe_Init(): Exit
# ssse-flw: Control Command EMBSE_LOG_LEVEL; requested log level = 4
# {"credentials":{"accessKeyId":"XXX","secretAccessKey":"XXX","expiration":"2024-07-10T07:07:03Z"}}

response="{${response#*{}"

# parse the response
#
tmp=${response#*'"accessKeyId":"'}
[ "$response" = "$tmp" ] && error "failed to get accessKeyId"
accessKeyId=${tmp%%\"*}
tmp=${response#*'"secretAccessKey":"'}
[ "$response" = "$tmp" ] && error "failed to get secretAccessKey"
secretAccessKey=${tmp%%\"*}
tmp=${response#*'"sessionToken":"'}
[ "$response" = "$tmp" ] && error "failed to get sessionToken"
sessionToken=${tmp%%\"*}

set --

# invoke the IoT Job DescriptExecution REST API
#
req_url="https://$IOT_JOB_ENDPOINT/things/$sn/jobs/$SWUPDATE_ARMADILLO_TWIN"
set -- "$@" -sS
set -- "$@" --http1.1 --tlsv1.2
set -- "$@" --aws-sigv4 "aws:amz:us-east-1:IotLaserThingJobManagerService"
set -- "$@" --user "$accessKeyId:$secretAccessKey"
set -- "$@" -H "X-Amz-Security-Token: $sessionToken"
set -- "$@" "$req_url"
response="$(curl "$@")"
# curl output example:
# {"execution":{"approximateSecondsBeforeTimedOut":null,"executionNumber":1,"jobDocument":"{\"version\":\"1.0\",\"steps\":[{\"action\":{\"name\":\"SWUpdate\",\"type\":\"runCommand\",\"input\":{\"url\":\"https://bucket.s3.us-east-1.amazonaws.com/XXX\",\"postAction\":\"wait\"}}}]}","jobId":"XXX","lastUpdatedAt":1720592696,"queuedAt":1720592694,"startedAt":1720592696,"status":"IN_PROGRESS","statusDetails":{"beforeVer":"XXX","waitingReboot":"0"},"thingName":null,"versionNumber":2}}

# parse the response
#
tmp=${response#*'"execution":'*'\"url\":\"'}
[ "$response" = "$tmp" ] && error "failed to get url"
url=${tmp%%\\\"*}

# output the renewed URL
#
printf "%s" "$url"

#
# End of File
#
