#!/usr/bin/env bash
# 文件名: ssh-key-access.sh

source $(realpath -m ..)/.vars.conf
source $(realpath -m ..)/.hosts.conf

ssh_key_type=ed25519
ssh_key_tag=gitee-deploy
ssh_key_file=/root/.ssh/id_ed25519
ssh_options=${ssh_options:-'-o StrictHostKeyChecking=no'}
ssh_root_pass=${ssh_root_pass:-'123456'}

# 判断sshpass 工具是否安装
sshpass --help >/dev/null 2>/dev/null
if [[ "$?" -ne "0" ]]
then
     printf "$err:请先安装sshpass,异常退出!\n"
     exit 67
fi

# 生成SSH密钥对
if [[ ! -e ${ssh_key_file} ]]
then
    printf "$info: 生成SSH创建密钥对"
    ssh-keygen -t ${ssh_key_type} -a 250 -C "${ssh_key_tag}"  -f ${ssh_key_file} -N "" >/dev/null
    chattr +i ${ssh_key_file}
fi


# 为集群节点添加SSH证书公钥
for ip in ${master_node_ip[@]} ${worker_node_ip[@]} ${registry_server}
do
    sshpass -p "${ssh_root_pass}" ssh -t ${ssh_options} root@${ip} "grep ${ssh_key_tag} ~/.ssh/authorized_keys" >/dev/null 2>/dev/null || \
    sshpass -p "${ssh_root_pass}" ssh-copy-id  ${ssh_options} -i ${ssh_key_file}.pub -f root@${ip} >/dev/null &
done
wait
