#!/usr/bin/env bash

STARTDATE=$(date)

set -euo pipefail

# wrapper script to set up the environment before calling one of the
# targets for the analysis dashboard

function find_zooxrc() {
        CURDIR=$(pwd)
        ZRC_CMD=""
        while [[ "$CURDIR" != ""  && "$ZRC_CMD" == "" ]]; do
                ZRC_CMD=$(find $CURDIR -name zooxrc.sh -print)
                CURDIR=${CURDIR%/*}
        done
        if [[ $ZRC_CMD != "" ]]; then
                echo $ZRC_CMD
        else
                echo false
        fi
}

SOURCECMD=$(find_zooxrc)
if [[ $SOURCECMD == false ]]; then
        exit 1
else
        source $SOURCECMD
fi

export DAD_PROD_DATABASE_PASSWORD=$(vault read -field=value secret/dad/production-us-west-1/postgres_password)
export DAD_PROD_DATABASE_URI="postgres://dad:$DAD_PROD_DATABASE_PASSWORD@internal-postgres.cp4rxnpmuhoe.us-west-1.rds.amazonaws.com:5432/dad"

export DAD_TEST_DATABASE_PASSWORD=$(vault read -field=value secret/dad-test/production-us-west-1/postgres_password)
export DAD_TEST_DATABASE_URI="postgres://dad-test:$DAD_TEST_DATABASE_PASSWORD@internal-postgres.cp4rxnpmuhoe.us-west-1.rds.amazonaws.com:5432/dad-test"

echo 'Have you done these things:'
echo '0. stop the dad-test ECS instance task using the console -- set the "Number of tasks" to zero'
echo 'https://us-west-1.console.aws.amazon.com/ecs/home?region=us-west-1#/clusters/production--internal-ecs/services/dad-test/update'
echo '1. cd //infra/terraform/internal_postgres_databases'
echo '2. terraform workspace select production:dad-test'
echo '# connect to the "dad-test" database as the owner'
echo '3. psql $DAD_TEST_DATABASE_URI'
echo '# connect to the "dad" database so you can drop dad-test'
echo '3a. dad-test=> \c dad'
echo '# ensure all the test database connections are dead so psql will let you drop the db'
echo '3b. dad=> SELECT pg_terminate_backend(pid)'
echo '          FROM pg_stat_activity           '
echo "          WHERE datname = 'dad-test';     "
echo '3c. dad=> drop database "dad-test";'
echo '# you may need to kill/drop a few times in a row unless you stopped all incoming services (see step zero)'
echo '3d. dad=> exit'
echo '4. terraform plan  # you should see that a new db will be created'
echo '5. terraform apply # the database will be created'
read -p "Ready to proceed (y/N): "
if [[ "$REPLY" != "y" ]]; then
  exit
fi

WORKDIR=$(mktemp -d /tmp/test-refresh-$(date +%y%m%d%H%M%S).XXXXXXXX)
echo saving output to $WORKDIR
echo ---------
cd $WORKDIR
echo begin dumping production database $(date)
pg_dump $DAD_PROD_DATABASE_URI -b -c -f dad-prod-dump.sql -v > prod_db_dump.stdoe 2>&1
echo end   dumping production database $(date)
echo ---------
sed "s/DATABASE dad/DATABASE dadtest/;s/\(^[^0-9].*dad\)\(;*$\)/\1test\2/g" dad-prod-dump.sql | sed 's/dadtest/"dad-test"/g' > dad-test-load.sql
echo begin loading test database $(date)
psql -a -d $DAD_TEST_DATABASE_URI -f dad-test-load.sql -L test_db_load.log > test_db_load.stdoe 2>&1
echo end   loading test database $(date)
echo ---------
echo started at $STARTDATE
echo finished at $(date)
echo ---------
echo '6. Either:'
echo '   a. deploy dad (see //web_apps/dad/README.md) or'
echo '   b. restore the "Number of tasks" via the UI in step zero.'
echo '7. brun //web_apps/dad:manage -- db stamp -d $ZOOX_WORKSPACE_ROOT/web_apps/dad/database/versions <version_of_desired_head_migration>'
echo '8. brun //web_apps/dad:manage -- db migrate'
echo '   which should result in the message:'
echo '     "INFO  [alembic.env] No changes in schema detected."'
