#!/usr/bin/env bash

# Copyright 2021 The KCP Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

export DEMO_DIR="$( dirname "${BASH_SOURCE[0]}" )"
source "${DEMO_DIR}"/../.setupEnv

source ${DEMOS_DIR}/demo-magic

TYPE_SPEED=30
#PROMPT_AFTER=1
DEMO_PROMPT="☸️ $ "

function pause() {
  if [[ -n "${NO_WAIT}" ]]; then
    sleep 2
  else
    if [[ -n "${1-}" ]]; then
      sleep "$1"
    else
      wait
    fi
  fi
}

export KUBECONFIG=${KUBECONFIG:-${KCP_DIR}/.kcp/admin.kubeconfig}
if ! kubectl get namespaces &>/dev/null; then
  echo "kcp server not started, run 'bin/kcp start'"
  exit 1
fi

kubectl config use-context admin  &>/dev/null

clear

pe "kubectl get pods"
pe "kubectl api-resources"

pe "kubectl apply -Rf ${DEMO_DIR}/external-integrations/"
kubectl wait crd/databases.postgresql.crossplane.io --for condition=established &>/dev/null
pe "kubectl explain database"

pause
clear

pe "kubectl config view --minify | grep server:"
pe "kubectl config use-context user"
pe "kubectl config view --minify | grep server:"
pe "kubectl get databases"
pe "kubectl get crds"

pause

clear

pe "kubectl config use-context admin"

pe "kubectl apply -f ${KCP_DIR}/config"

kubectl wait crd/workloadclusters.workload.kcp.io --for condition=established &>/dev/null
kubectl wait crd/negotiatedapiresources.apiresource.kcp.io --for condition=established &>/dev/null
kubectl wait crd/apiresourceimports.apiresource.kcp.io --for condition=established &>/dev/null

pe "head -n 15 ${CLUSTERS_DIR}/us-west1.yaml"
pe "kubectl apply -f ${CLUSTERS_DIR}/us-west1.yaml"
pe "head -n 15 ${CLUSTERS_DIR}/us-east1.yaml"
pe "kubectl apply -f ${CLUSTERS_DIR}/us-east1.yaml"

pe "kubectl wait cluster/us-west1 --for condition=Ready --timeout=60s"
pe "kubectl wait cluster/us-east1 --for condition=Ready --timeout=60s"

pe "kubectl api-resources"

pe "kubectl create namespace demo"
pe "cat ${DEMO_DIR}/deployment.yaml"

pe "kubectl apply -f ${DEMO_DIR}/deployment.yaml -n demo"

until [[ "$(kubectl get deployments/my-deployment -n demo -o=jsonpath='{.status.updatedReplicas}')" == "10" ]]; do sleep 3; done

pe "kubectl get deployments -n demo"

pe "kubectl wait deployments --all -n demo --for=condition=Available --timeout=180s"
sleep 10

pe "kubectl get deployments -n demo"

pe "kubectl get pods"

pause
