#!/usr/bin/env bash

set -euo pipefail

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

if [[ ${DAD_ENVIRONMENT:="is missing"} == "development" ]]; then
        DB_NAME="dad-develop"
        unset DAD_DATABASE_URI
else
       if  [[ $DAD_ENVIRONMENT == "test" ]]; then
               DB_NAME="dad-test"
       elif [[ $DAD_ENVIRONMENT == "production" ]]; then
               DB_NAME="dad"
       else
               echo "Invalid environment DAD_ENVIRONMENT=$DAD_ENVIRONMENT . Possible environments are development, test and production"
               exit 1
       fi
       export DAD_DATABASE_PASSWORD=$(vault read -field=value secret/${DB_NAME}/production-us-west-1/postgres_password)
       export DAD_DATABASE_URI=${DAD_DATABASE_URI:-"postgres://${DB_NAME}:${DAD_DATABASE_PASSWORD}@internal-postgres.cp4rxnpmuhoe.us-west-1.rds.amazonaws.com:5432/dad"}
fi

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

cd $ZOOX_WORKSPACE_ROOT/web_apps/dad

target="$1"
shift

function die() {
  echo "$1"
  exit 1
}

function cleanup() {
  rm "$runcmd"
}

# example command:
# bazel_run "$target" -- "$@"

runcmd="$(mktemp /tmp/bazel-run.XXXXXX)" || die "Could not create tmp file"
trap "cleanup" EXIT

bazel_err=0
bazel_out=$(bazel run --script_path="$runcmd" "$target" -- "$@"  2>&1) || bazel_err=$?
if [ $bazel_err -ne 0 ]
then
  echo "Bazel error"
  echo "$bazel_out"
  exit $bazel_err
fi

[ -x "$runcmd" ] || die "File $runcmd not executable"

"$runcmd"
