#!/bin/bash

set -e

varfile="$HOME/.eventbus-vars.sh"

usage_env_vars() {
    echo "  DB_HOST     to select a different DB cluster"
    echo "  DB_NAME     to select a different DB name (default: eventbus)"
    echo "  TC          to change the teleport cluster"
    echo "  SSH_USER    to change your LDAP user"
    echo "  INSTANCE_ID to change which instance to jump to"
    echo
}

if [[ ! -f "$varfile" ]]; then
    echo "!!! Make sure to set up $varfile correctly"
    exit 1
fi

source "$varfile"

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

if [[ "$1" = "production" ]]; then
    export TC=${TC:-twitch-eventbus-prod-uswest2}
    export DB_HOST=${DB_HOST:-$PROD_DB_HOST}
    export INSTANCE_ID=${INSTANCE_ID:-$PROD_INSTANCE_ID}
elif [[ "$1" = "staging" ]]; then
    export TC=${TC:-twitch-eventbus-dev-uswest2}
    export DB_HOST=${DB_HOST:-$STAGING_DB_HOST}
    export INSTANCE_ID=${INSTANCE_ID:-$STAGING_INSTANCE_ID}
else
    echo "USAGE: $0 <production|staging>"
    echo
    echo "Customization of various parameters is possible through env vars:"
    echo
    usage_env_vars
    exit 1
fi

echo "DB_NAME=${DB_NAME}"
echo "DB_HOST=${DB_HOST}"
echo "SSH_USER=${SSH_USER}"

if [[ -z "$INSTANCE_ID" || -z "$DB_HOST" ]]; then
    echo "######"
    echo "Variables not configured properly."
    echo "Either pass them using env vars or edit the defaults"
    echo "by filling them into $varfile".
    echo "######"
    usage_env_vars
    exit 1
fi

aws ssm start-session \
    --target "${INSTANCE_ID}" \
    --document-name AWS-StartInteractiveCommand \
    --parameters command="sudo docker run -it --rm postgres:10 psql postgresql://twitch@${DB_HOST}/${DB_NAME}"