#!/bin/bash
BASE=/opt/ai-deployer

if [[ -f /usr/bin/expect ]];then
  logger warn "expect is already installed!"
else
  #安装expect
  if [[ `cat /etc/os-release` =~ CentOS ]];then
    tar zxf "$BASE/down/centos-rpm-packages/expect-rpm-packages.tar.gz" -C "$BASE/down/centos-rpm-packages"
    rpm -ivh --force --nodeps $BASE/down/centos-rpm-packages/expect-rpm-packages/*
  elif [[ `cat /etc/os-release` =~ openEuler ]];then
    #tar zxf "$BASE/down/ubuntu-deb-packages/expect-deb-packages.tar.gz" -C "$BASE/down/ubuntu-deb-packages"
    #dpkg -i $BASE/down/ubuntu-deb-packages/expect-deb-packages/*
    yum install expect -y
  else
    apt install expect -y
  fi
fi

#配置heketi密钥对
if [[ ! -f /etc/heketi/heketi_key.pub ]];then
  if [[ `cat /etc/os-release` =~ CentOS ]];then
    ssh-keygen -f /etc/heketi/heketi_key -t rsa -N ''
    chown heketi:heketi /etc/heketi/heketi_key*
  elif [[ `cat /etc/os-release` =~ Ubuntu ]];then
    ssh-keygen -m PEM -t rsa -b 4096 -q -f /etc/heketi/heketi_key -N ''
    chown heketi:heketi /etc/heketi/heketi_key*
  else
    echo "使用ed25519的加密方式"
    ssh-keygen -t ed25519 -q -f /etc/heketi/heketi_key -N ''
    chown heketi:heketi /etc/heketi/heketi_key*
  fi  
fi

serverIPs=$(grep -E 'STORAGE_NODE_IP' $BASE/ai.config |cut -d'=' -f2|awk '!($1 in IP){IP[$1];print $1}')
serverPassword=$(grep -r 'SERVER_PASSWORD' $BASE/ai.config)
serverPassword=${serverPassword#*=}
sshPort=$(grep -r 'SSH_PORT' $BASE/ai.config |cut -d'=' -f2|awk '{print $1}')

#将生成的密钥发送至目标服务器,自动输入yes和密码
auto_ssh_copy_id() {
  expect -c "set timeout -1
  spawn ssh-copy-id -i /etc/heketi/heketi_key.pub -p $sshPort $1
  expect {
    *yes/no* {send -- yes\r;exp_continue;}
    *password:* {send -- $2\r;exp_continue;}
    eof        {exit 0;}
  }"
}
#遍历需要发送密钥的服务器
ssh_copy_id_to_all(){
  for serverIP in $serverIPs
  do
    auto_ssh_copy_id $serverIP $serverPassword
  done
}
ssh_copy_id_to_all

