#!/usr/bin/env bash

# Example usage:
# Environment=dev bash lambda/reprocess_vector_orders/execute.sh 1436914,1437618 false
# Make sure 'Environment' env var is set.

# Fail on emty vars or non-zero exist status of any command.
set -e -u

if [ $# -ne 2 ]; then
    echo 1>&2 "Expecting comma separated order IDs and a reprocess flag"
    echo 1>&2 "Usage: $0 order_id_1,order_id_2,... true|false"
    exit 2
fi

OUTPUT_LOG="lambda-output.log"
DO_REPROCESS="$2"

# Join by comma and enclose each ID in double quotes to make it suitable for a JSON array.
ORDER_IDS='"'$(echo $1 | sed 's/,/","/g')'"'

PAYLOAD="{\"order_ids\":[${ORDER_IDS}],\"do_reprocess\":${DO_REPROCESS}}"

# Note: lambda-result.log would just contain 'null'.
LAMBDA_CMD="\
    aws lambda invoke \
    --region us-east-1 \
    --invocation-type RequestResponse \
    --function-name ${Environment}-vector-reprocess-orders \
    --payload ${PAYLOAD} \
    --log-type Tail \
    lambda-result.log"

${LAMBDA_CMD} > ${OUTPUT_LOG}

# Decode and show Lambda output log.
cat ${OUTPUT_LOG} | python -c 'import sys, json; print(json.load(sys.stdin)["LogResult"])' | base64 --decode
