#!/bin/bash

set -e

API="https://api.fr.cloud.gov"
ORG="gsa-acq-eqip"

#
# Determine what environment to configure based on the repo/branch
#
if [ "$CIRCLE_BRANCH" = "master" ]; then
		if [ "$CIRCLE_PROJECT_USERNAME" = "18F" ]; then
				SPACE="production"
				API_NAME="eqip-prototype-api"
				API_MANIFEST="conf/manifests/api.yml"
				FRONTEND_NAME="eqip-prototype"
				FRONTEND_MANIFEST="conf/manifests/frontend.yml"
		elif [ "$CIRCLE_PROJECT_USERNAME" = "truetandem" ]; then
				SPACE="staging"
				API_NAME="eqip-prototype-api-staging"
				API_MANIFEST="conf/manifests/api-staging.yml"
				FRONTEND_NAME="eqip-prototype-staging"
				FRONTEND_MANIFEST="conf/manifests/frontend-staging.yml"
		fi
elif [ "$CIRCLE_BRANCH" = "develop" ]; then
		SPACE="dev"
		API_NAME="eqip-prototype-api-dev"
		API_MANIFEST="conf/manifests/api-dev.yml"
		FRONTEND_NAME="eqip-prototype-dev"
		FRONTEND_MANIFEST="conf/manifests/frontend-dev.yml"
		CF_USERNAME=$CF_USERNAME_DEV
		CF_PASSWORD=$CF_PASSWORD_DEV
else
		echo "No deployment target"
		exit
fi

# Add the JWT_SECRET to the manifest
echo "    JWT_SECRET: $(openssl rand -base64 32)" >> $API_MANIFEST

# This directory is used to persist the CF credentials
mkdir -p $HOME/.cf

# This wonderful image pulls the `cf` tool along with the
# `autopilot` plugin
docker pull adelevie/cf-cli:latest

# For some reason, aliases aren't working here
# so we're using this function instead
cf_run() {
		docker run \
					 --rm \
					 -v $HOME/.cf:/root/.cf \
					 -v $PWD:/app \
					 adelevie/cf-cli \
					 cf "$@"
}

cf_run login -a $API -u $CF_USERNAME -p $CF_PASSWORD -o $ORG -s $SPACE
cf_run zero-downtime-push $API_NAME -f $API_MANIFEST
cf_run zero-downtime-push $FRONTEND_NAME -f $FRONTEND_MANIFEST
