#!/usr/bin/env bash

##############################################################################
#
# DESCRIPTION
#   This script:
#       - Downloads the GCP credentials JSON from AWS Secrets Manager
#       - Saves the JSON from the secret to a file in the parent directory
#       - Sets the GOOGLE_APPLICATION_CREDENTIALS environment variable
#
#   There are optional overrides that can be set via environment variables.
#
#   These are the available override variables and their defaults:
#       ENVIRONMENT             "dev"
#       AWS_GCP_SECRET_NAME     "delphi/${ENV}/gcp/${GCP_CREDENTIALS_NAME}"
#       GCP_CREDENTIALS_NAME    "external-bigtable-reader"
#       GCP_CREDENTIALS_FILE    "../${GCP_CREDENTIALS_NAME}.json"
#
##############################################################################

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" > /dev/null && pwd)"
PARENT_DIR="$(dirname ${SCRIPT_DIR})"

# get variable from environment, or default to 'dev'
ENVIRONMENT="${ENVIRONMENT:-dev}"

GCP_CREDENTIALS_NAME_DEFAULT='external-bigtable-reader'
# get variable from environment, or default to 'external-bigtable-user'
GCP_CREDENTIALS_NAME="${GCP_CREDENTIALS_NAME:-$GCP_CREDENTIALS_NAME_DEFAULT}"
# where to store the credentials file
GCP_CREDENTIALS_FILE_DEFAULT="${PARENT_DIR}/${GCP_CREDENTIALS_NAME}.json"
# get variable from environment, or default to parent directory file location
GCP_CREDENTIALS_FILE=${GCP_CREDENTIALS_FILE:-$GCP_CREDENTIALS_FILE_DEFAULT}

AWS_SECRET_NAME_DEFAULT="delphi/${ENVIRONMENT}/gcp/${GCP_CREDENTIALS_NAME}"
AWS_GCP_SECRET_NAME=${AWS_GCP_SECRET_NAME:-$AWS_SECRET_NAME_DEFAULT}

# get the json secret value from AWS (binary)
AWS_SECRETS_RESPONSE=$(aws secretsmanager get-secret-value --secret-id "${AWS_GCP_SECRET_NAME}" --output json)
AWS_SECRET_JSON=$(echo ${AWS_SECRETS_RESPONSE} | jq -r -c .SecretString )

# dump the decoded base64 output to a json file
echo ${AWS_SECRET_JSON} > ${GCP_CREDENTIALS_FILE}

# set our env var to the location of the json file
export GOOGLE_APPLICATION_CREDENTIALS="${GCP_CREDENTIALS_FILE}"
