#!/bin/bash

##拷贝ansible相关文件##
sh install_ansible.sh
cp -f config /etc/ansible/k8s-install.config

##获取k8s节点信息##
eval $(cat /etc/ansible/k8s-install.config | grep -v "^#" | sed -n '/^\[k8s-master\]/,/^$/p' | awk -F' ' '/^[0-9]/ {i++;S[i]=$0;print "S["i"]=" "\""S[i]"\""}')
num=${#S[@]}

eval $(cat /etc/ansible/k8s-install.config | grep -v "^#" | sed -n '/^\[k8s-node\]/,/^$/p' | awk -F' ' '/^[0-9]/ {j++;T[j]=$0;print "T["j"]=" "\""T[j]"\""}')
num2=${#T[@]}

eval $(cat /etc/ansible/k8s-install.config | grep -v "^#" | sed -n '/^\[harbor\]/,/^$/p' | awk -F' ' '/^[0-9]/ {j++;H[j]=$0;print "H["j"]=" "\""H[j]"\""}')
harbor=${#H[@]}

##配置ansible的hosts文件的ip##
sed  -i '/\[k8s-master\]/,/^$/c \[k8s-master\]' /etc/ansible/hosts
sed  -i '/\[k8s-master\]/G' /etc/ansible/hosts
sed  -i '/\[k8s-node\]/,/^$/c \[k8s-node\]' /etc/ansible/hosts
sed  -i '/\[k8s-node\]/G' /etc/ansible/hosts
for j in `seq 1 ${num}`;do
        sed "/\[k8s-master\]/a\\${S[j]}" -i /etc/ansible/hosts
done
for i in `seq 1 ${num2}`;do
        sed "/\[k8s-node\]/a\\${T[i]}" -i /etc/ansible/hosts
done

##获取master节点的hostname##
for j in `seq 1 ${num}`;do
    ip=`echo ${S[j]} | awk -F' ' '{print $1}'` 
    hostname[$j]=`ansible $ip -m shell -a "hostname" | sed -n "2, 1p" | awk '{print $1}'`
done
##获取node节点的hostname##
for i in `seq 1 ${num2}`;do
    ip=`echo ${T[i]} | awk -F' ' '{print $1}'`
        hostname2[$i]=`ansible $ip -m shell -a "hostname" | sed -n "2, 1p" | awk '{print $1}'`
done

##配置ansible的hosts文件的hostname##
sed  -i '/\[k8s-master\]/,/^$/c \[k8s-master\]' /etc/ansible/hosts 
sed  -i '/\[k8s-master\]/G' /etc/ansible/hosts
sed  -i '/\[k8s-node\]/,/^$/c \[k8s-node\]' /etc/ansible/hosts
sed  -i '/\[k8s-node\]/G' /etc/ansible/hosts
for j in `seq 1 ${num}`;do
    sed "/\[k8s-master\]/a\\${S[j]} hostname=${hostname[j]} order=$j" -i /etc/ansible/hosts
done
for i in `seq 1 ${num2}`;do
        sed "/\[k8s-node\]/a\\${T[i]} hostname=${hostname2[i]}" -i /etc/ansible/hosts
done

##配置ansible的hosts文件的harborhost##
harbor_ip=`cat /etc/ansible/k8s-install.config |grep harbor_order|awk '{print $1}'`
if [ ${harbor} -gt 0 ];then
    sed "s/harborhost\=/&\"$harbor_ip\"/" -i /etc/ansible/k8s-install.config
fi

/usr/bin/ansible-playbook -b /etc/ansible/addnode.yaml