#!/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}"

__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"
    echo "$__tmp_kubeconfig"
}

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