#!/bin/bash

echo "Backup certs"
cp -R /etc/kubernetes/ssl /etc/kubernetes/ssl.backup
cp /etc/kubernetes/admin.conf /etc/kubernetes/admin.conf.backup
cp /etc/kubernetes/controller-manager.conf /etc/kubernetes/controller-manager.conf.backup
cp /etc/kubernetes/kubelet.conf /etc/kubernetes/kubelet.conf.backup
cp /etc/kubernetes/scheduler.conf /etc/kubernetes/scheduler.conf.backup
cp /root/.kube/config /root/.kube/config.backup

echo "## Expiration before renewal ##"
kubeadm alpha certs check-expiration

echo "## Renewing certificates managed by kubeadm ##"
kubeadm alpha certs renew all

echo "## Restarting control plane pods managed by kubeadm ##"
crictl pods --namespace kube-system --name 'kube-scheduler-*|kube-controller-manager-*|kube-apiserver-*|etcd-*' -q | /usr/bin/xargs crictl rmp -f

echo "## Updating /root/.kube/config ##"
#kubeadm alpha kubeconfig user --client-name kubernetes-admin --org system:masters > /etc/kubernetes/admin.conf
cp /etc/kubernetes/admin.conf ~/.kube/config

echo "## Waiting for apiserver to be up again ##"
until printf "" 2>>/dev/null >>/dev/tcp/127.0.0.1/6443; do sleep 1; done

echo "## Expiration after renewal ##"
kubeadm alpha certs check-expiration
