#!/bin/bash
##############################################
# 脚本名称：get_rdma_order_by_ip.sh
# 版本：1.1
# 作者：frankydyang
# 日期：2023-06-21
# 描述：通过免密ssh获取各节点rdma信息，输出重新排序节点信息
##############################################
# 检查输入参数是否为空
if [ $# -eq 0 ]; then
    echo "请输入要读取的文本文件名作为参数，文本每行只存储一个ip address值。"
    echo "ip重新排序结果将写入hostfile.txt。"
    echo "支持第二参数-trace作为开关,使能将rdma hash值存储至hostfile.txt中。"
    exit 1
fi

# 读取文本文件内容
file="$1"
host_ids=()
#获取本地ip
local_ip=$(hostname -I | awk '{print $1}')
# rdma magic字符串
magicstring="rdma-la-group-"
TRACE="$2"

rm -f hostfile.txt

# 检查是否可以免密执行
check_auth() {
    if [[ $local_ip != $1 ]]; then
        #非本地ip
       ssh -o StrictHostKeyChecking=no -o PasswordAuthentication=no -o ConnectTimeout=5 "$1" "echo Successful" >/dev/null 2>&1
       # 检查返回值
       if [ $? -ne 0 ]; then
           echo "无法免密登录到 $1"
           exit
       fi
    fi
}
# 通过SSH执行命令获取ID
execute_ssh_command() {
    if [[ $local_ip == $1 ]]; then
        #本地ip，直接curl
        ssh_result=$(curl http://metadata.tencentyun.com/latest/meta-data/rdma-la-group)
    else
        #远程ip，通过ssh curl
        ssh_result=$(ssh -o StrictHostKeyChecking=no "$1" "curl http://metadata.tencentyun.com/latest/meta-data/rdma-la-group")
    fi
    #echo "$ssh_result"
    host_id=$(echo "$ssh_result" | tr -d '\n')  # 去掉换行符
    # 判断是否存在rdmaSwitch信息
    if [[ "$host_id" != *"$magicstring"* ]]; then
        echo "Can not get rdmaSwitch info. Please check if $1 is the HCC type host."
        exit
    fi
    #去掉rdma前缀
    hash_value="${host_id/$magicstring/}"
    #echo "$host_id"
    host_ids+=("$1:$hash_value")
}

for ip in `cat $file`
do
    check_auth "$ip"
    execute_ssh_command "$ip"
done

#排序并存储至hostfile.txt中
if [[ "$TRACE" == "-trace" ]]; then
  echo "${host_ids[@]}" | tr ' ' '\n' | sort -k 2 -t :  >> hostfile.txt
else
  hostfile_string=$(echo "${host_ids[@]}" | tr ' ' '\n' | sort -k 2 -t :)
  while IFS=: read -r key value; do
      echo "$key" >> hostfile.txt
  done <<< "$hostfile_string"
fi
