#!/bin/bash

set -e

AWS="aws --region us-west-2"


if [[ "$ENVIRONMENT" != "staging" ]] && [[ "$ENVIRONMENT" != "production" ]]; then
    echo "invalid environment '$ENVIRONMENT'"
    exit 1
fi

if [[ "${S3_BUCKET}" = "" ]]; then
    echo "no S3_BUCKET set in environment"
    exit 1
fi

# Make sure our s3 bucket is accessible
${AWS} s3 ls ${S3_BUCKET} >> /dev/null

start=$(python -c 'from datetime import *; print((datetime.combine(date.today(), time()) + timedelta(days=-1)).isoformat())')
end=$(python -c 'from datetime import *; print(datetime.combine(date.today(), time()).isoformat())')
echo Creating EventBus badges using the time range $start to $end

events=$(${AWS} cloudwatch list-metrics --namespace AWS/SNS  | jq -r '.Metrics[].Dimensions[].Value' | sort | grep $ENVIRONMENT | uniq)

for event in $events; do

    events_per_day=$(${AWS} cloudwatch get-metric-statistics --namespace AWS/SNS --metric-name NumberOfMessagesPublished \
    --start-time $start --end-time $end --period 86400 --statistics Sum \
    --dimensions Name=TopicName,Value=$event | jq '.Datapoints[].Sum')
    if [[ $events_per_day -gt 999 ]]; then
        count="$(( events_per_day / 1000 ))K"
    elif [[ $events_per_day -gt 0 ]]; then
        count=$events_per_day
    else
        count=0
    fi

    event_name=$(echo $event | sed 's/.*[-_]//')
    image=${event_name}.svg
    curl -s -o $image "https://img.shields.io/badge/EventBus:$event_name-${count}_events/day-informational.svg?style=for-the-badge&logo=Twitch"
    echo "generated $image (${count}_events/day)"
    ${AWS} s3 cp $image s3://${S3_BUCKET}
    ${AWS} s3api put-object-acl --bucket ${S3_BUCKET} --key $image  --acl public-read
done






