#!/bin/bash

# Copyright Istio 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.

vm_driver="kvm2"

case "${OSTYPE}" in
  darwin*) vm_driver="hyperkit";;
  linux*)
    ;;
  *) echo "unsupported: ${OSTYPE}" ;;
esac

# Virtual machine driver, the default value is decided by your OS type if it's not specified,
# e.g.:
#   hyperkit default to darwin os
#   kvm2 default to Debian or Ubuntu os
# Besides, you can set any vm-driver you like via exporting `VM_DRIVER` for your environment.
VM_DRIVER=${VM_DRIVER:-${vm_driver}}

echo "Using ${VM_DRIVER} as VM for Minikube."

# Delete any previous minikube cluster
minikube delete

echo "Starting Minikube."

# Start minikube
SUDO_PREFIX=""
if [[ "${VM_DRIVER}" == "none" ]]; then
  # When minikube runs in `--vm-driver=none` mode, it requires root permission.
  SUDO_PREFIX="sudo -E"
fi

$SUDO_PREFIX minikube start \
    --extra-config=apiserver.enable-admission-plugins="NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota" \
    --kubernetes-version=v1.14.0 \
    --insecure-registry="localhost:5000" \
    --cpus=4 \
    --memory=8192 \
    --vm-driver="$VM_DRIVER"

#Setup docker to talk to minikube
eval "$(minikube docker-env)"

while ! kubectl get pods -n kube-system | grep kube-proxy |  grep Running > /dev/null; do
  echo "kube-proxy not ready, will check again in 5 sec"
  sleep 5
done

# Set up env ISTIO if not done yet
if [[ -z "${ISTIO// }" ]]; then
  if [[ -z "${GOPATH// }" ]]; then
    echo GOPATH is not set. Please set and run script again.
    exit
  fi
  export ISTIO=$GOPATH/src/istio.io
  echo 'Set ISTIO to' "$ISTIO"
fi

echo "Host Setup Completed"
