#!/bin/bash

OPERATION=$1

STEP_FUNC_NAME="HelloWorld"
STEP_FUNC_URL="http://localhost:8083"
STEP_FUNC_CALL="aws stepfunctions --endpoint $STEP_FUNC_URL"

S3_BUCKET='test'
S3_URL="http://localhost:4567"
S3_CALL="aws s3api --endpoint $S3_URL"

AWS_ACCOUNT_ID=123456789012
AWS_REGION="us-east-1"

set -e

if [ "$OPERATION" = "setup" ]; then

    # read args and input data
    STEPS_FILE=${2:-"steps.json"}
    RAW_INPUT=$(cat $STEPS_FILE)
    INPUT=$(echo $RAW_INPUT | jq -j tojson)

    # start step function container and dependencies
    docker-compose up -d --build step-functions
    sleep 3

    # create step function definition
    DUMMY_ROLE="arn:aws:iam::$AWS_ACCOUNT_ID:role/DummyRole"
    RESULT=$($STEP_FUNC_CALL create-state-machine --role-arn $DUMMY_ROLE --definition $(cat steps.json | jq -j tojson) --name $STEP_FUNC_NAME)
    echo $RESULT | jq

    # create s3 bucket (custom for this app)
    RESULT=$($S3_CALL create-bucket --bucket $S3_BUCKET --region $AWS_REGION)
    echo $RESULT | jq

    # enable bucket versioning to experiment with
    RESULT=$($S3_CALL put-bucket-versioning --bucket $S3_BUCKET --versioning-configuration "{\"Status\": \"Enabled\"}")
    echo $RESULT | jq

    # shutdown
    echo ""
    echo "Setup complete!"
    echo ""
    echo "Press any key to stop running containers"
    read ANYKEY
    docker-compose down

elif [ "$OPERATION" = "exec" ]; then

    # read args and input data
    INPUT_FILE=${2:-"input.json"}
    STEP_FUNC_EXEC=${3:-"$INPUT_FILE-default"}
    RAW_INPUT=$(cat $INPUT_FILE)
    INPUT=$(echo $RAW_INPUT | jq -j tojson)

    # execute state machine
    STEP_FUNC_ARN="arn:aws:states:$AWS_REGION:$AWS_ACCOUNT_ID:stateMachine:$STEP_FUNC_NAME"
    RESULT=$($STEP_FUNC_CALL start-execution --state-machine $STEP_FUNC_ARN --input $INPUT --name $STEP_FUNC_EXEC)
    echo $RESULT | jq

    # watch progress until done
    HISTORY_CMD="$STEP_FUNC_CALL get-execution-history --execution-arn arn:aws:states:$AWS_REGION:$AWS_ACCOUNT_ID:execution:$STEP_FUNC_NAME:$STEP_FUNC_EXEC"
    CURRENT_CMD="$HISTORY_CMD --max-items 1 --reverse-order"

    while true; do
        CURRENT_STATE=$($CURRENT_CMD | jq -r .events[0].type)
        echo $CURRENT_STATE
        if [ "$CURRENT_STATE" = "ExecutionSucceeded" ] || [ "$CURRENT_STATE" = "ExecutionFailed" ]; then
            break
        fi
        sleep 5
    done

    # display full execution history
    $HISTORY_CMD --max-items 1000 | jq

    # show the ascii image result (custom for this app)
    if [ "$CURRENT_STATE" = "ExecutionSucceeded" ]; then
        $CURRENT_CMD | jq -r .events[0].executionSucceededEventDetails.output | jq -r .image
    fi

elif [ "$OPERATION" = "stop" ]; then

    docker-compose down

else
    echo "Unrecognized command \"$OPERATION\""
    exit 1
fi
