#!/bin/bash

nowDate=`date +%Y%m%d_%H%M%S`
k8sDir=/etc/kubernetes
etcdDir=/etc/ssl
kubeadm=/usr/local/bin/kubeadm

echo "[ Current Cert Info ]"
$kubeadm alpha certs check-expiration --config /etc/kubernetes/kubeadm-config.yaml
echo ""
echo "[ Working History ]"
cp -arp $k8sDir "$k8sDir"_"$nowDate"
cp -arp $etcdDir "$etcdDir"_"$nowDate"
$kubeadm alpha certs renew admin.conf
$kubeadm alpha certs renew apiserver
$kubeadm alpha certs renew apiserver-kubelet-client
$kubeadm alpha certs renew controller-manager.conf
$kubeadm alpha certs renew front-proxy-client
$kubeadm alpha certs renew scheduler.conf
$kubeadm alpha kubeconfig user --client-name system:kube-controller-manager > /etc/kubernetes/controller-manager.conf
$kubeadm alpha kubeconfig user --client-name system:kube-scheduler > /etc/kubernetes/scheduler.conf
$kubeadm alpha kubeconfig user --client-name system:node:$(hostname) --org system:nodes > /etc/kubernetes/kubelet.conf
kill -s HUP $(/usr/sbin/pidof kube-apiserver)
kill -s HUP $(/usr/sbin/pidof kube-controller-manager)
kill -s HUP $(/usr/sbin/pidof kube-scheduler)
rm -rf ~/.kube/config
cp -arp /etc/kubernetes/admin.conf ~/.kube/config
chown $(id -u):$(id -g) $HOME/.kube/config
chmod 777 $HOME/.kube/config
cp -arp /var/lib/kubelet/pki /var/lib/kubelet/pki_"$nowDate"
rm -rf /var/lib/kubelet/pki/kubelet*
systemctl restart kubelet
systemctl restart etcd
echo ""
echo "[ Changed Cert Info ]"
$kubeadm alpha certs check-expiration --config /etc/kubernetes/kubeadm-config.yaml
