#!/bin/bash
set -e
echo ">>>> Initial Config Start <<<<"

echo "[TASK 1] Clear root authorized_keys (no password SSH login expected)"
[ -f /root/.ssh/authorized_keys ] && : > /root/.ssh/authorized_keys || true

echo "[TASK 2] Change Timezone & Setting Profile & Bashrc"
ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
echo 'alias vi=vim' >> /etc/profile
echo "sudo su -" >> /home/ubuntu/.bashrc

echo "[TASK 3] Disable ufw & AppArmor"
if systemctl is-active --quiet ufw; then
  systemctl stop ufw && systemctl disable ufw
else
  echo "ufw is not active or installed, skipping"
fi
if systemctl is-active --quiet apparmor; then
  systemctl stop apparmor && systemctl disable apparmor
else
  echo "apparmor is not active or installed, skipping"
fi

echo "[TASK 4] Install Packages"
apt-get update
apt-get install -y tree jq bridge-utils net-tools bat exa duf nfs-common sysstat netcat-openbsd python3-pip
echo "alias cat='batcat --paging=never'" >> /etc/profile

echo "[TASK 5] Install aws-cfn-bootstrap (for cfn-signal)"
pip3 install --break-system-packages \
  https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz \
  || pip3 install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz

echo "[TASK 6] Setting Local DNS Using Hosts file"
echo "192.168.10.10 k8s-m" >> /etc/hosts
echo "192.168.10.101 k8s-w1" >> /etc/hosts
echo "192.168.10.102 k8s-w2" >> /etc/hosts
echo "192.168.20.103 k8s-w3" >> /etc/hosts

echo "[TASK 7] Install containerd.io"
cat <<EOF > /etc/modules-load.d/containerd.conf
overlay
br_netfilter
EOF
modprobe overlay
modprobe br_netfilter

cat <<EOF > /etc/sysctl.d/99-kubernetes-cri.conf
net.bridge.bridge-nf-call-iptables  = 1
net.ipv4.ip_forward                 = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF
sysctl -p /etc/sysctl.d/99-kubernetes-cri.conf

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg --yes
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list
apt-get update
apt-get install -y containerd.io
mkdir -p /etc/containerd
containerd config default > /etc/containerd/config.toml

echo "[TASK 8] Using the systemd cgroup driver"
sed -i 's/SystemdCgroup = false/SystemdCgroup = true/g' /etc/containerd/config.toml
systemctl restart containerd

cat <<EOF > /etc/default/kubelet
KUBELET_KUBEADM_ARGS=--container-runtime=remote --container-runtime-endpoint=/run/containerd/containerd.sock --cgroup-driver=systemd
EOF

cat <<EOF > /etc/crictl.yaml
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
EOF

echo "[TASK 9] Install Kubernetes components (kubeadm, kubelet, kubectl) — auto-pick latest patch in series"
apt-mark unhold kubelet kubeadm kubectl 2>/dev/null || true

# Use the minor (e.g. 1.28) of $KUBERNETES_VERSION for the apt repo, but auto-resolve actual package version
KUBE_MINOR="${KUBERNETES_VERSION%.*}"  # 1.28.0 -> 1.28
curl -fsSL "https://pkgs.k8s.io/core:/stable:/v${KUBE_MINOR}/deb/Release.key" \
  | gpg --dearmor -o /usr/share/keyrings/kubernetes-archive-keyring.gpg --yes
echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v${KUBE_MINOR}/deb/ /" \
  | tee /etc/apt/sources.list.d/kubernetes.list
apt-get update

# Resolve to the latest available package version that matches $KUBERNETES_VERSION-* (e.g. 1.28.0-1.1)
KUBE_PKG_VER=$(apt-cache madison kubelet | awk '{print $3}' | grep "^${KUBERNETES_VERSION}-" | head -1)
if [ -z "$KUBE_PKG_VER" ]; then
  # Fallback: latest patch available for the minor (e.g. 1.28.x)
  KUBE_PKG_VER=$(apt-cache madison kubelet | awk '{print $3}' | grep "^${KUBE_MINOR}\." | head -1)
fi
echo "Resolved kubelet package version: $KUBE_PKG_VER"

apt-get install -y --allow-change-held-packages \
  kubelet="$KUBE_PKG_VER" kubeadm="$KUBE_PKG_VER" kubectl="$KUBE_PKG_VER"

apt-mark hold kubelet kubeadm kubectl
systemctl enable kubelet && systemctl start kubelet

echo ">>>> Initial Config End <<<<"
