#!/bin/bash

start_node=$1 # 指定开始的节点
end_node=$2 # 指定结束的节点
# 指定输出文件名
filename=IBTest_cn${start_node}-cn${end_node}_$(date '+%Y-%m-%d_%H:%M:%S').out 

rm -rf $filename
touch $filename

# 等待一小段时间方便tail 查看完整输出
sleep 20

echo "" >> $filename
echo "############################################################" >> $filename
echo "### FileName: batchIB.sh                                 ###" >> $filename 
echo "### Function: Batch Test IB Performance For HPC          ###" >> $filename
echo "### Write By qiql, 2022-10-22                            ###" >> $filename
echo "### Base: pdsh                                           ###" >> $filename
echo "############################################################" >> $filename

echo "### Output File: $filename" >> $filename
echo "### Current Directory: $(pwd)" >> $filename
echo "### Node Range: cn${start_node} -- cn${end_node}" >> $filename
echo "### Test Start: $(date '+%Y-%m-%d %H:%M:%S')" >> $filename
echo "" >> $filename

# title 做表头
printf "%-8s" "host" >> $filename
# 因为是从058-076 前面有0，所以要指定10进制，否则shell会以8进制进行解析然后报错
for (( i=10#${start_node};i<=10#${end_node};i++ ))
do
    # 需要在前面自动补0以填写完整的主机号
    host=`echo ${i} | awk '{printf("%03d",$0)}'`;
    printf "%-10s" "cn${host}" >> $filename
done
echo "" >> $filename
cat $filename
# title

for (( i=10#${start_node};i<=10#${end_node};i++ ))
do
    host_i=`echo ${i} | awk '{printf("%03d",$0)}'`;
    printf "%-8s" "cn${host_i}" >> $filename
    for (( j=10#${start_node};j<=10#${end_node};j++ ))
    do
        if [ $i == $j ];
        then
	    printf "%-10s" "self" >> $filename
        else
            host_j=`echo ${j} | awk '{printf("%03d",$0)}'`;
            pdsh -w cn${host_i} kill -9 `lsof -i:18515 | grep ib_w | awk -F " " '{printf $2}'`
            pdsh -w cn${host_i} ib_write_bw -a &
            pdsh -w cn${host_j} kill -9 `lsof -i:18515 | grep ib_w | awk -F " " '{printf $2}'`
            out=`pdsh -w cn${host_j} ib_write_bw -a cn${host_i} | grep 8388608 | awk -F " " '{printf $5}'`
            if [ ! -n "$out" ]; then
                printf "%-10s" "error" >> $filename
            else
		printf "%-10s" "$out" >> $filename
            fi
        fi
    done
    echo "" >> $filename
done
echo "" >> $filename
echo "############################################################" >> $filename
echo "### All Test have been finished!" >> $filename
echo "### Test   End: $(date '+%Y-%m-%d %H:%M:%S')" >> $filename
echo "############################################################" >> $filename

