#!/bin/bash

# @ssh_key_create
# Create ssh public and private key. RSA nopass.

function ssh_key_create() {
    if [ ! -f /root/.ssh/id_rsa ]; then
        ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
    fi
}

# @ssh_key_config
# Copy public key to other host.
function ssh_key_config() {
    ssh_key_create
    IP_LIST_CLONE=(IP ${IP_LIST[@]})
    #string_check ${IP_LIST_CLONE[@]}
    for ip in ${IP_LIST[@]}; do
        echo "============"$ip
        echo $SSH_PORT
        echo ${SSH_OPT}
        USER=$(get_node_attribute "$REGION" $ip user)
        PASSWORD=$(get_node_attribute "$REGION" $ip password)
        echo ${USER}
        echo ${PASSWORD}
        #sed -i /${ip}/d /root/.ssh/known_hosts &>/dev/null
        expect -c "
          set timeout 1;
          spawn ssh ${USER}@${ip};
          expect {
            *yes/no* { send \"yes\r\"; exp_continue }
            *password:* { send \"$PASSWORD\r\" }  
          }
          exit
          interact
        "
        echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        echo "sshpass -p {root passowrd} ssh-copy-id -p $SSH_PORT ${SSH_OPT} ${USER}@${ip}"
        echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        sshpass -p ${PASSWORD} ssh-copy-id -p $SSH_PORT ${SSH_OPT} ${USER}@${ip}
        sleep 1
    done
    node_hostname_list="${K8S_MASTER01} ${K8S_MASTER02} ${K8S_MASTER03} ${K8S_NODE01} ${K8S_NODE02} ${K8S_NODE03}"
    for node_hostname in $node_hostname_list; do
        echo "============"$node_hostname
        USER=$(get_node_attribute "$REGION" $ip user)
        PASSWORD=$(get_node_attribute "$REGION" $ip password)
        expect -c "
          set timeout 1;
          spawn ssh ${USER}@${node_hostname};
          expect {
            *yes/no* { send \"yes\r\"; exp_continue }
            *password:* { send \"$PASSWORD\r\" }  
          }
          exit
          interact
        "
    done
}

ssh_key_config
