#! /bin/bash

define(){ IFS='\n' read -r -d '' ${1} || true; }

define service_account <<'SCRIPT'
apiVersion: v1
kind: ServiceAccount
automountServiceAccountToken: true
metadata:
  name: tiller
imagePullSecrets:
- name: regcred
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: tiller
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
  - kind: ServiceAccount
    name: tiller
    namespace: kube-system
SCRIPT

rm -rf .tmp/config
mkdir -p .tmp/config

export KUBE_NAMESPACE=${KUBE_NAMESPACE:-default}

if [ "$CI_SERVER_NAME" == "GitLab" ]; then
  echo "$service_account" > .tmp/config/service_account.yaml
  # 
  kubectl --namespace $KUBE_NAMESPACE apply -f .tmp/config
else
  kubectl --namespace $KUBE_NAMESPACE apply -f $PWD/scripts/k8s/.config/
fi

if [ "$HELM_INSTALL" == "yes" ]; then
  helm init --upgrade --tiller-namespace $KUBE_NAMESPACE --service-account tiller
fi

if [ "$CI_SERVER_NAME" == "GitLab" ]; then
  secret_name="gitlab-registry"
  if kubectl get --namespace $KUBE_NAMESPACE secret $secret_name &>/dev/null; then 
      kubectl --namespace $KUBE_NAMESPACE get -o json serviceaccounts tiller | jq -rM '.imagePullSecrets[1].name = "gitlab-registry"' | kubectl apply -f -
      kubectl --namespace $KUBE_NAMESPACE describe serviceaccounts tiller
  fi
fi

kubectl --namespace $KUBE_NAMESPACE get serviceaccounts,secret
helm version

rm -rf .tmp/config