#!/bin/bash

# Easy access to environment databases.

usage() {
cat << EOF

  psql.sh [ PALOLO_ENV ]

     Connects to the database associated with the given environment.

     PALOLO_ENV defaults to "local".

     Note that in order to connect to an RDS database (prod, demo, staging, etc.)
     you *must* be on the relevant VPN.

EOF
}

set -eo pipefail

cd $(dirname $0)

ENV=$1

if [[ "$ENV" == "--help" ]]; then
  usage
  exit 0
elif [ -z "$ENV" ]; then
  ENV=local
else
  read -rp "Confirm target environment: " ENV_CHECK
  if [ "$ENV" != "$ENV_CHECK" ]; then
    echo "Environment mismatch"
    exit 1
  fi
fi

if [ "$DEBUG" = "1" ]; then
  set -x
fi

db_write=false
while test $# != 0
do
    case "$1" in
    --dbWrite) db_write=true; break;;
    esac
    shift
done

echo "Extracting secrets..."
if $db_write; then
  echo "[DANGER] Using read/write database credentials in ${ENV}. Be careful!"
  env_output=$(pnpm --silent run secrets ${ENV} --dump --dbWrite)
else
  env_output=$(pnpm --silent run secrets ${ENV} --dump)
fi

PUBLIC_PALOLO_ENV=$(grep "PUBLIC_PALOLO_ENV" <<< "$env_output" | cut -d "=" -f 2 | sed -r "s/\'|\"//g")
DATABASE_URL=$(grep "DATABASE_URL" <<< "$env_output" | cut -d "=" -f 2  | sed -r "s/\'|\"//g")

if [ -z "${DATABASE_URL?}" ]; then
  echo "DATABASE_URL not set.  Please run \`pnpm run secrets\` first."
  exit 1
fi

# user:pass@host:port/dbname?schema=public and psql doesn't understand that schema bit
ACTUAL_URL=$(echo ${DATABASE_URL} | sed 's|\(.*\)?.*|\1|')

echo "Connecting to ${ACTUAL_URL?}..."
echo
psql ${ACTUAL_URL}
