#!/bin/bash

if [ $# -lt 4 ]
  then
    echo "You must provide four arguments: Lambda function name, MSK cluster ARN, kafka topic names, stream starting position."
    echo "Example: create_msk_trigger.sh \"my-lambda-function\" \"arn:abcd12345\" \"topic1,topic2\" \"TRIM_HORIZON\""
    exit 1
fi

IFS=","
LAMBDA_FUNCTION=$1
MSK_CLUSTER_ARN=$2
KAFKA_TOPICS=$3
START_POSITION=$4


for topic in $KAFKA_TOPICS
do
  echo "Verifying if trigger for $topic exists.."
  EXISTS=$(aws lambda list-event-source-mappings --function-name "${LAMBDA_FUNCTION}" --query="EventSourceMappings[?Topics[0]==\`${topic}\`].Topics[0]" --output=text)
  if [ $? -ne 0 ]
  then
    echo "Could not determine topic existence." >&2
    exit 1
  fi

  if [ -z "$EXISTS" ] || [ "$EXISTS" = 'False' ]
  then
    echo "Trigger for $topic does not exist, creating it.."
    aws lambda create-event-source-mapping --function-name "$LAMBDA_FUNCTION" --topics "$topic" --event-source-arn "$MSK_CLUSTER_ARN" --starting-position "$START_POSITION" --query="EventSourceMappings[].UUID" --enabled
    if [ $? -eq 0 ]
    then
      echo "Trigger for topic $topic created."
    else
      echo "Could not create trigger for topic." >&2
      exit 1
    fi
  else
    echo "Trigger for topic $topic already exists."
  fi
done
unset IFS

echo "Lambda triggers creation finished."
