#!/usr/bin/env bash

if [ ! $# -ge 1 ]; then
    echo "usage: $0 cluster [helm args]"
    exit 1
fi

k='kubectl --context oceanbox'

name=$1
ns=$name-vcluster
shift

yq ".clusters[]|select(.name|contains(\"$name-vcluster\")).name" ~/.kube/config | grep -q "$name"

if [ $? = 0 ]; then
    $k get ns $ns >/dev/null 2>&1 || $k create ns $ns
    # helm template -n $ns $@ $name oceanbox/atlantis-vcluster | $k apply -f -
    helm template -n $ns $@ $name ../charts/vcluster | $k apply -f -

    echo "waiting for vcluster $name to appear... "
    while true; do
        $k wait -n $ns --for=condition=ready pod -l app=vcluster 2>&1 > /dev/null
        if [ $? != 0 ]; then
            echo "zzz..."
            sleep 15
        else
            break
        fi
    done
    vcluster connect $name-vcluster -- kubectl -n dapr-system wait pod --for=condition=ready -l app=dapr-operator
    echo "wating 20s for Dapr..."
    sleep 20
    tmp=/tmp/$name-vlcuster.tmp$$
    kubectl kustomize ../resources/atlantis/manifests/staging > $tmp
    vcluster connect $name-vcluster -- kubectl apply -f $tmp
    rm $tmp
else
    cat << EOF
***
*** $name-vcluster must be defined in ~/.kube/config
***
clusters:
- cluster:
    insecure-skip-tls-verify: true
    server: https://$name-vcluster.beta.oceanbox.io
  name: $name-vcluster
contexts:
- context:
    cluster: $name-vcluster
    namespace: atlantis
    user: oidc
  name: $name-vcluster
users:
- name: oidc
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      args:
      - oidc-login
      - get-token
      - --oidc-issuer-url=https://login.microsoftonline.com/3f737008-e9a0-4485-9d27-40329d288089/v2.0
      - --oidc-client-id=9b6daef0-02fa-4574-8949-f7c1b5fccd15
      - --oidc-client-secret=[redacted]
      command: kubectl
EOF
fi


