#!/usr/bin/env bash
set -euo pipefail

pushd "$(dirname "$0")/.." >/dev/null
service="$(basename "$PWD")"

cd deploy

PROJECT="${PROJECT:-$(gcloud config get-value project)}"
CLUSTER_NAME="${CLUSTER_NAME:-""}"

if [[ -z "$PROJECT" ]] ; then
    echo "no GCP project configured. please set PROJECT" >&2
    exit 1
fi

if [[ -z "$CLUSTER_NAME" ]] ; then
  cluster_names=$(gcloud container clusters list --format json | jq -r '.[] | .name')
  if [[ 1 == $(echo "$cluster_names" | wc -l) ]] ; then
    CLUSTER_NAME="$cluster_names"
  else
    echo "Multiple clusters are available please provide the CLUSTER_NAME" >&2
    exit 1
  fi
fi
ZONE=${ZONE:-$(gcloud container clusters list --format json | jq -r ".[] | select(.name == \"$CLUSTER_NAME\") | .zone")}

gcloud container clusters get-credentials "$CLUSTER_NAME" --zone "$ZONE"

REGISTRY="gcr.io/${PROJECT}"
VERSION="demo"
NO_IMAGE_PUSH=${NO_IMAGE_PUSH:-""}

image="dbaas-${service}-server:local"
tagless="$(echo "$image" | cut -d : -f 1)"
new_image="$REGISTRY/$tagless:$VERSION"
if [[ -z $NO_IMAGE_PUSH ]] ; then
docker tag "$image" "$new_image"
gcloud docker -- push "$new_image"
fi

if ! output=$(kubectl create namespace "$service" 2>&1) ; then
  if ! echo "$output" | grep AlreadyExists >/dev/null ; then
    echo "$output"
    exit 1
  fi
  sleep 10
fi

# There should be a nice way to do this instead of delete+create
# This only works if the image changes
# kubectl -n dbaas set image deployments/dbaas dbaas="$new_image"
if kubectl get deployment -n "$service" "$service" ; then
  cat manifests/dbaas-${service}-deploy.yaml \
    | sed "s|gcr.io/smooth-tendril-207212/dbaas-${service}-server:latest|$new_image|" \
    | kubectl delete -n "$service" -f  -
fi
cat manifests/dbaas-${service}-deploy.yaml \
  | sed "s|gcr.io/smooth-tendril-207212/dbaas-${service}-server:latest|$new_image|" \
  | kubectl apply -n "${service}" -f  -

SERVER_ONLY=${SERVER_ONLY:-}
if [[ $SERVER_ONLY == 1 ]] ; then
  echo "deployed just the server"
  exit 0
fi

kubectl -n "${service}" apply -f manifests/deps
sleep 2
kubectl get pod -n "${service}"
