#!/bin/bash

ARN=$1
EVENT_TYPE=$2
ENVIRONMENT=$3
MESSAGE_NAME=$4
FIELD_NAME=$5

if [[ "$ARN" == "" ]]; then
  echo "./local-create-subscriber-grant.sh <arn> <event_type> <environment> <message_name> <field_name>"
  exit 1
fi

if [[ "$EVENT_TYPE" == "" ]]; then
  echo "./local-create-subscriber-grant.sh <arn> <event_type> <environment> <message_name> <field_name>"
  exit 1
fi

if [[ "$ENVIRONMENT" == "" ]]; then
  echo "./local-create-subscriber-grant.sh <arn> <event_type> <environment> <message_name> <field_name>"
  exit 1
fi

if [[ "$MESSAGE_NAME" == "" ]]; then
  echo "./local-create-subscriber-grant.sh <arn> <event_type> <environment> <message_name> <field_name>"
  exit 1
fi

if [[ "$FIELD_NAME" == "" ]]; then
  echo "./local-create-subscriber-grant.sh <arn> <event_type> <environment> <message_name> <field_name>"
  exit 1
fi

# Fake creds
export AWS_ACCESS_KEY_ID=foobar
export AWS_SECRET_ACCESS_KEY=foobar
export AWS_SESSION_TOKEN=foobar

curl --request "POST" -s \
    --location "http://localhost:8888/twirp/code.justin.tv.eventbus.controlplane.infrastructure.Infrastructure/CreateAuthorizedFieldSubscriberGrant" \
    --header "Content-Type:application/json" \
    --data "{\"event_type\":\"${EVENT_TYPE}\",\"environment\":\"${ENVIRONMENT}\",\"iam_role\":\"${ARN}\",\"authorized_field\":{\"message_name\":\"${MESSAGE_NAME}\",\"field_name\":\"${FIELD_NAME}\"}}" \
    --header "Twitch-Ldap-User: controlplane-updater" \
    --header "Twitch-Ldap-Groups: WyJ0ZWFtLWV2ZW50YnVzIl0=" # base64 encoded JSON groups (controlplane-updater)
