#!/bin/bash

set -e

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

TS=$(date +%s)

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 "  BOUNCE_HOST to change the SSH bounce host"
    echo "  SSH_USER    to change your LDAP user"
    echo "  INSTANCE_ID to select an instance for SSM to jump to"
    echo
}

if [[ ! -f "$varfile" ]]; then
    for varname in PROD_DB_HOST PROD_BOUNCE_HOST STAGING_DB_HOST STAGING_BOUNCE_HOST; do
        echo "${varname}=" >> $varfile
    done
    echo "created $varfile"
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 BOUNCE_HOST=${BOUNCE_HOST:-$PROD_BOUNCE_HOST}
    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 BOUNCE_HOST=${BOUNCE_HOST:-$STAGING_BOUNCE_HOST}
    export INSTANCE_ID=${INSTANCE_ID:-$STAGING_INSTANCE_ID}
else
    echo "USAGE: $0 <production|staging> [migration count]"
    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 "BOUNCE_HOST=${BOUNCE_HOST}"
echo "INSTANCE_ID=${INSTANCE_ID}"
echo "SSH_USER=${SSH_USER}"

if [[ -z "$INSTANCE_ID" || -z "$BOUNCE_HOST" || -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

echo "===="
echo "Copying migrations to bounce host."
ssh "${SSH_USER}@${BOUNCE_HOST}" rm -rf ./migrations
scp -r ./internal/db/postgres/migrations "${SSH_USER}@${BOUNCE_HOST}":/tmp/migrations-${TS}

echo "===="
echo "About to run migrations"

echo -n "DB Password: " 
read -s db_password
echo

aws ssm start-session \
    --target "${INSTANCE_ID}" \
    --document-name AWS-StartInteractiveCommand \
    --parameters command="sudo docker run --rm -v /tmp/migrations-${TS}:/migrations migrate/migrate -path=/migrations/ -verbose -database postgres://twitch:${db_password}@${DB_HOST}/${DB_NAME} up $2"
