#!/bin/bash -e
#
# 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.

source $(dirname "${0}")/common/helpers

mktemp_kubeconfig
kubeconfig="$__tmp_kubeconfig"
mktemp_tls_dir
tls_dir="$__tmp_tls_dir"

trap cleanup_kubeconfig EXIT
trap cleanup_tls_dir EXIT

apiserver_flags="
  --authentication-kubeconfig $kubeconfig \
  --authorization-kubeconfig $kubeconfig \
  --cluster-identity=gardener-local-${USER} \
  --authorization-always-allow-paths=/healthz \
  --kubeconfig $kubeconfig \
  --secure-port=8443 \
  --tls-cert-file $tls_dir/tls.crt \
  --tls-private-key-file $tls_dir/tls.key \
  --v 2"

if [[ "$(uname -s)" == "Linux" && "$(uname -r)" =~ "microsoft-standard" ]]; then
  apiserver_flags="${apiserver_flags} \
  --bind-address=127.0.0.1"
fi

ld_flags="$("$(dirname $0)"/../get-build-ld-flags.sh)"
case $(k8s_env) in
    $KIND)
        echo "Found kind ..."
        kubectl -n garden port-forward service/etcd 32379:2379 > /dev/null &
        trap "kill -9 $! > /dev/null" EXIT
        GO111MODULE=on go run \
          -mod=vendor \
          -ldflags "$ld_flags" \
          "$(dirname $0)"/../../cmd/gardener-apiserver/main.go \
          --etcd-servers http://localhost:32379 \
          $apiserver_flags
        ;;
    $DOCKER_FOR_DESKTOP)
        echo "Found Docker Kubernetes ..."
        GO111MODULE=on go run \
          -mod=vendor \
          -ldflags "$ld_flags" \
          "$(dirname $0)"/../../cmd/gardener-apiserver/main.go \
          --etcd-servers http://localhost:32379 \
          $apiserver_flags
        ;;
    $MINIKUBE)
        echo "Found Minikube ..."
        GO111MODULE=on go run \
          -mod=vendor \
          -ldflags "$ld_flags" \
          "$(dirname $0)"/../../cmd/gardener-apiserver/main.go \
          --etcd-servers http://$(minikube ip):32379 \
          $apiserver_flags
        ;;
    $NODELESS)
        echo "Found Nodeless Kubernetes ..."
        GO111MODULE=on go run \
          -mod=vendor \
          -ldflags "$ld_flags" \
          "$(dirname $0)"/../../cmd/gardener-apiserver/main.go \
          --etcd-servers http://localhost:22379 \
          $apiserver_flags
        ;;
esac
