#!/bin/bash

# Copyright 2017 The Openstack-Helm 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.
set -xe

source /etc/kube-role
if [[ "${KUBE_ROLE}" == "master" ]]; then
  # Source network vars
  source /etc/kube-cni

  # Define k8s version
  source /etc/kube-version
  if [[ "${KUBE_VERSION}" == "default" ]]; then
    KUBE_VERSION_FLAG=""
  else
    KUBE_VERSION_FLAG="--kubernetes-version=${KUBE_VERSION}"
    echo "We will use K8s ${KUBE_VERSION}"
  fi

  echo 'Setting up K8s'
  source /etc/kubeapi-device
  if [[ "$KUBE_BIND_DEV" != "autodetect" ]]; then
    KUBE_BIND_IP=$(ip addr list ${KUBE_BIND_DEV} |grep "inet " |cut -d' ' -f6|cut -d/ -f1)
    echo 'We are going to bind the K8s API to: ${KUBE_BIND_IP}'
    kubeadm init ${KUBE_VERSION_FLAG} \
      --skip-preflight-checks \
      --pod-network-cidr ${CNI_POD_CIDR} \
      --api-advertise-addresses ${KUBE_BIND_IP}
  else
    kubeadm init ${KUBE_VERSION_FLAG} \
      --skip-preflight-checks \
      --pod-network-cidr ${CNI_POD_CIDR}
  fi

  echo 'Setting up K8s client'
  cp /etc/kubernetes/admin.conf /root/
  export KUBECONFIG=/root/admin.conf

  echo 'Marking master node as schedulable'
  kubectl taint nodes --all node-role.kubernetes.io/master-

  echo 'Installing Calico CNI'
  kubectl apply -f /opt/cni-manifests/${KUBE_CNI}.yaml

  echo 'Setting Up Cluser for OpenStack-Helm dev use'
  /usr/bin/openstack-helm-dev-prep
elif [[ "${KUBE_ROLE}" == "worker" ]]; then
  source /etc/kubeadm-join-command-args
  kubeadm join --skip-preflight-checks ${KUBEADM_JOIN_ARGS}
fi
