. /etc/init.d/functions
# 从 Ansible 主机文件中提取 IP 地址到 /tmp/hosts.txt
awk -F '=' '/ansible_ssh_host/{print $2 }' /etc/ansible/hosts > /tmp/hosts.txt

# 检查本地是否存在 SSH 密钥对,如果不存在则生成
if [ ! -f ~/.ssh/id_rsa ]; then
  echo "未找到 SSH 密钥对,正在生成..."
  ssh-keygen -t rsa -b 4096 -N "" -f ~/.ssh/id_rsa >/dev/null 2>&1
else
  echo "SSH 密钥对已存在,跳过生成步骤..."
fi

# 判断是否安装了 sshpass
if ! command -v sshpass &> /dev/null; then
  echo "sshpass 未安装,正在安装 sshpass..."
  if command -v yum &> /dev/null; then
    yum install -y sshpass
  else
    echo "请手动安装 sshpass。"
    exit 1
  fi
fi

# 读取主机是否在线
echo "读取主机是否在线"
while IFS= read -r host; do
  if [ -n "$host" ]; then
    ping -c1 -w1 $host  &>/dev/null && action $host /bin/true || action $host /bin/false
  fi
done < /tmp/hosts.txt

# 提示用户输入 SSH 密码  可以写在循环中 一台一台输入密码  
read -sp "请输入 SSH 密码: " PASSWORD
echo

# 读取主机列表并推送公钥
echo "正在推送id_rsa.pub"
while IFS= read -r host; do
  if [ -n "$host" ]; then
    sshpass -p "$PASSWORD" ssh-copy-id -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa.pub "$host" &>/dev/null && action $host /bin/true || action $host /bin/false
  fi
done < /tmp/hosts.txt

echo "所有主机的 SSH 公钥推送完成。"