# bin/setup_environment

echo "Establishing environment ..."

# NOTE:  $RAILS_ENV must be set before this script is sourced; otherwise it
#        will always default to development.  It is also important that
#        every variable assignment begin with 'export ' in order to
#        reuse that file in bash scripts.

# NOTE:  The environment variable $APP_ROOT must also be set AND all of the
#        .env* files must be in that directory.

# NOTE:  The RACK_ENV and RAILS_ENV variables are expected to have the same value; but,
#        this is not a requirement.

if [ "xyzzy" = "xyzzy$RACK_ENV" ]; then
  export RACK_ENV=development
fi

if [ "xyzzy" = "xyzzy$RAILS_ENV" ]; then
  export RAILS_ENV=development
fi

# NOTE: Using $DEPLOY_TYPE to specifically target a deployment host.
#       Examples of DEPLOY_TYPE values are: sqa. uat, dev, docker

if [ "xyzzy" = "xyzzy$DEPLOY_TYPE" ]; then
  export DEPLOY_TYPE=localhost
fi


# NOTE: the file order is backward from the ruby gem dotenv because
#       in bash its the last value that sticks as "official"

for env_file in "${APP_ROOT}/.env" \
                "${APP_ROOT}/.env.${RAILS_ENV}" \
                "${APP_ROOT}/.env.${DEPLOY_TYPE}" \
                "${APP_ROOT}/.env.local" \
                "${APP_ROOT}/.env.${RAILS_ENV}.local" \
                "${APP_ROOT}/.env.${DEPLOY_TYPE}.local" ; do

  # Only source files that exist.
  if [ -f $env_file ]; then
    echo "  Sourcing `basename $env_file` ..."
    source $env_file
  fi

done
