# this is based on https://computingforgeeks.com/deploy-kubernetes-cluster-on-ubuntu-with-kubeadm/
# https://blog.knoldus.com/how-to-install-kubernetes-on-ubuntu-20-04-kubeadm-and-minikube/

# prepare repos for Kubernetes
sudo apt -y install curl apt-transport-https
curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list

# install Kubernetes
sudo apt update
sudo apt -y install kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl

# disable swap, probably already off
swapoff -a

# enable kernel modules
modprobe overlay
modprobe br_netfilter

# add some settings to sysctl
sudo tee /etc/sysctl.d/kubernetes.conf<<EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF

# reload sysctl
sudo sysctl --system

# add Docker repo and install its packages
sudo apt install -y gnupg2 software-properties-common apt-transport-https ca-certificates
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt update
sudo apt install -y containerd.io docker-ce docker-ce-cli

# create required directories
sudo mkdir -p /etc/systemd/system/docker.service.d

# create daemon json config file
sudo tee /etc/docker/daemon.json <<EOF
{
    "exec-opts": ["native.cgroupdriver=systemd"],
    "log-driver": "json-file",
    "log-opts": {
        "max-size": "100m"
    },
    "storage-driver": "overlay2",
}
EOF

# start and enable docker ervices
sudo systemctl daemon-reload
sudo systemctl restart docker
sudo systemctl enable docker

# enable some plugin that is needed for j8s 1.25:
# https://serverfault.com/questions/1074008/containerd-1-4-9-unimplemented-desc-unknown-service-runtime-v1alpha2-runtimese
sudo tee /etc/containerd/config.toml <<EOF
[plugins."io.containerd.grpc.v1.cri"]
    systemd_cgroup = true
EOF
sudo systemctl restart containerd

# enable kubelet service.
sudo systemctl enable kubelet

# pull container images
sudo kubeadm config images pull

# bootstrap a cluster without using DNS endpoint
sudo kubeadm init --pod-network-cidr=192.168.0.0/16

# point path to kube config
mkdir ~/.kube
sudo cat /etc/kubernetes/admin.conf | tee ~/.kube/config

# check status
kubectl cluster-info

# install Calico network plugin
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/master/manifests/tigera-operator.yaml
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/master/manifests/custom-resources.yaml  # this file also is using 192.168.0.0/16 as CIDR
kubectl get pods -n calico-system

# confirm master node is ready
kubectl get nodes -o wide
