#!/bin/bash

ENVIRONMENT="$1"

case $ENVIRONMENT in
    staging)
        CLUSTER="twitch-eventbus-dev-uswest2"
        ASSUMED_ROLE_ARN_PREFIX="arn:aws:sts::297385687169:assumed-role/Admin"
        ;;
    production)
        CLUSTER="twitch-eventbus-prod-uswest2"
        ASSUMED_ROLE_ARN_PREFIX="arn:aws:sts::859517684765:assumed-role/Admin"
        ;;
    *)
        echo "Must pass 'staging' or 'production' as an argument"
        exit 1
esac

ASSUMED_ROLE=$(aws sts get-caller-identity | jq -r .Arn)
if [[ "$?" != "0" ]]; then
    echo "Error getting STS caller identity"
    exit 1
fi

if ! [[ "${ASSUMED_ROLE}" =~ ^${ASSUMED_ROLE_ARN_PREFIX}.* ]]; then
    echo "Unexpected assume role: ${ASSUMED_ROLE}"
    echo "Do you have Isengard credentials setup for the wrong environment?"
    exit 1
fi

if [ -z "$AWS_ACCESS_KEY_ID" ] || [ -z "$AWS_SECRET_ACCESS_KEY" ] || [ -z "$AWS_SESSION_TOKEN" ]; then
    echo "Environment must contain Isengard credentials: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN"
    exit 1
fi

export SSH_USER=${SSH_USER:-$(whoami)}

GOOS=linux GOARCH=amd64 go build -o eventbus-admin main.go
chmod +x ./eventbus-admin

TC=${CLUSTER} ssh -t ${SSH_USER}@jumpbox "\
    mkdir -p \${HOME}/.bin ; \
    export PATH=\"\$PATH:\$HOME/.bin\"; \
    export ENVIRONMENT=\"${ENVIRONMENT}\"; \
    export AWS_ACCESS_KEY_ID=\"${AWS_ACCESS_KEY_ID}\"; \
    export AWS_SECRET_ACCESS_KEY=\"${AWS_SECRET_ACCESS_KEY}\"; \
    export AWS_SESSION_TOKEN=\"${AWS_SESSION_TOKEN}\"; \
    aws s3 cp s3://eventbus-admin-cli-${ENVIRONMENT}/bin/eventbus-admin \${HOME}/.bin/eventbus-admin ; \
    chmod +x \${HOME}/.bin/eventbus-admin ; \
    bash"

