#!/bin/bash
#
# Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
#
# 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.

set -e

DOCKER_FOR_DESKTOP="docker-for-desktop"
MINIKUBE="minikube"
KIND="kind"
KIND_NODE_NAME_SUFFIX="-control-plane"
NODELESS="nodeless"

API_SERVER_SECURE_PORT="${API_SERVER_SECURE_PORT:-8443}"
ADMISSION_CONTROLLER_SECURE_PORT="${CONTROLLER_MANAGER_SECURE_PORT:-2721}"

__k8s_nodename=""
k8s_nodename() {
    if [[ "$__k8s_nodename" != "" ]]; then
        echo "$__k8s_nodename"
        return
    fi

    nodes_len=$(kubectl get node -o json | jq ".items" | jq '. | length')
    if [[ "$nodes_len" == "0" ]]; then
      echo $NODELESS
      return
    fi

    echo "$(kubectl get node -o json | jq ".items[0].metadata.name")" |  tr -d \"
}

k8s_env() {
    node_name=$(k8s_nodename)
    # for minikube >= v1.8.0 the default node name is "m01", for minikube < v1.8.0 - "minikube"
    if [[ "$node_name" == "$MINIKUBE" || "$node_name" == "m01" ]]; then
        echo "$MINIKUBE"
        return
    fi
    if [[ "$node_name" == *"$KIND_NODE_NAME_SUFFIX" ]]; then
        echo "$KIND"
        return
    fi
    if [[ "$node_name" == "docker"* ]]; then
        echo "$DOCKER_FOR_DESKTOP"
        return
    fi
    if [[ "$node_name" == "$NODELESS" ]]; then
      echo $NODELESS
      return
    fi

    >&2 echo "Unsupported Kubernetes Environment: $__k8s_env"
    return 1
}

k8s_username() {
    case $(k8s_env) in
        $KIND)
            ;;
        $DOCKER_FOR_DESKTOP)
            echo "$(k8s_nodename)"
            ;;
        $MINIKUBE)
            ;;
    esac
}

__tmp_kubeconfig=""
mktemp_kubeconfig() {
    if [[ "$__tmp_kubeconfig" != "" ]]; then
        echo "$__tmp_kubeconfig"
        return
    fi
    __tmp_kubeconfig="$(mktemp)"
    kubectl config view --raw > "$__tmp_kubeconfig"
}

cleanup_kubeconfig() {
    if [[ "$__tmp_kubeconfig" != "" ]]; then
        rm -f "$__tmp_kubeconfig"
        __tmp_kubeconfig=""
    fi
}

__tmp_tls_dir=""
mktemp_tls_dir() {
    if [[ "$__tmp_tls_dir" != "" ]]; then
        echo "$__tmp_tls_dir"
        return
    fi
    __tmp_tls_dir="$(mktemp -d)"

    local current_context="$(kubectl config view -o jsonpath='{.current-context}')"
    local current_user="$(kubectl config view -o jsonpath='{.contexts[?(@.name == "'"$current_context"'")].context.user}')"
    kubectl config view -o jsonpath='{.users[?(@.name == "'"$current_user"'")].user.client-certificate-data}' --raw | base64 -d > "$__tmp_tls_dir/tls.crt"
    kubectl config view -o jsonpath='{.users[?(@.name == "'"$current_user"'")].user.client-key-data}' --raw | base64 -d > "$__tmp_tls_dir/tls.key"
}

cleanup_tls_dir() {
    if [[ "$__tmp_tls_dir" != "" ]]; then
        rm -rf "$__tmp_tls_dir"
        __tmp_tls_dir=""
    fi
}

cleanup_controller_manager_webhook() {
  local CONTROLLER_MANAGER_SERVICE_NAME="gardener-controller-manager"
  local CONTROLLER_MANAGER_ENDPOINT_NAME="gardener-controller-manager"

  if kubectl -n garden get endpoints "$CONTROLLER_MANAGER_ENDPOINT_NAME" &> /dev/null; then
    kubectl -n garden delete endpoints $CONTROLLER_MANAGER_ENDPOINT_NAME
  fi
  if kubectl -n garden get services "$CONTROLLER_MANAGER_SERVICE_NAME" &> /dev/null; then
    kubectl -n garden delete services "$CONTROLLER_MANAGER_SERVICE_NAME"
  fi

  if kubectl get validatingwebhookconfiguration "gardener-controller-manager" &> /dev/null; then
    kubectl delete validatingwebhookconfiguration "gardener-controller-manager"
  fi
}
