#!/bin/bash

# Stop and disable firewalld
systemctl stop firewalld
systemctl disable firewalld

# sync time
timedatectl set-timezone Asia/Shanghai
timedatectl set-local-rtc 0
systemctl restart rsyslog
systemctl restart crond

# Disable SELinux temporarily
setenforce 0

# add eth0
sudo ip addr add 43.138.214.237/24 dev eth0 label eth0:0
sudo ip link set dev eth0:0 up

ip a

# Disable swap
swapoff -a

# Set hostname
hostnamectl set-hostname k8s-master

# Enable IP forwarding
echo "1" > /proc/sys/net/ipv4/ip_forward

# Add hosts entries
cat <<EOF >> /etc/hosts
43.136.97.177 k8s-node1
43.138.214.237 k8s-master
EOF

# Install Docker
yum remove -y docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine
rm -rf /etc/yum.repos.d/*
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
wget -P /etc/yum.repos.d/ http://mirrors.aliyun.com/repo/epel-7.repo
wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum clean all && yum makecache fast
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum install -y docker-ce-18.09.9 docker-ce-cli-18.09.9 containerd.io

# Configure Docker
mkdir -p /etc/docker
tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://pue18cfq.mirror.aliyuncs.com"],
  "exec-opts": ["native.cgroupdriver=systemd"]
}
EOF

# Enable and restart Docker
systemctl enable docker.service
systemctl daemon-reload
systemctl restart docker

# Install Kubernetes components
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
EOF
yum install -y kubelet-1.16.4 kubeadm-1.16.4 kubectl-1.16.4

# Enable and start kubelet service
systemctl enable kubelet
systemctl start kubelet

# Configure kubectl completion and make it effective
echo "source <(kubectl completion bash)" >> ~/.bash_profile
source ~/.bash_profile

# Configure bridge traffic to iptables
cat <<EOF > /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
vm.overcommit_memory=1 # 不检查物理内存是否够用
vm.panic_on_oom=0 # 开启 OOM
net.ipv4.ip_forward=1
net.ipv4.tcp_tw_recycle=0
net.ipv6.conf.all.disable_ipv6=1 # 关闭IPV6协议
EOF

# Apply sysctl configuration
sysctl -p /etc/sysctl.d/k8s.conf

echo " congratulations success"
