#!/bin/bash
#
cluster_ip=192.168.251.34,192.168.251.36,192.168.251.247
tcp_port=22,2379
#udp_port=32471

exec 7>&1
exec >> /tmp/network-monitor.txt

command -v nc &> /dev/null
if [ $? -ne 0 ]; then
    echo "can not find command nc, install the nc command first."
    exit 11
fi


nc_probe(){
    for ip in $(echo $cluster_ip | tr ',' ' '); do
         ip -4 a | grep $ip &> /dev/null
         if [ $? -eq 0 ]; then
             self=$ip
         fi
    done

    for ip in $(echo $cluster_ip | tr ',' ' '); do
         if [ "$ip" != "$self" ]; then
              for t_port in $(echo $tcp_port | tr ',' ' '); do
                  nc -z -v -n -w 5 $ip $t_port &> /dev/null
                  if [ $? -ne 0 ]; then
                      echo "[$(date +'%F %T')]: $self use nc connect to $ip tcp port $t_port failed."
                  else
                      echo "[$(date +'%F %T')]: $self use nc connect to $ip tcp port $t_port success."
                  fi
              done

              for u_port in $(echo $udp_port | tr ',' ' '); do
                   nc -u -z -v -n -w 5 $ip $u_port &> /dev/null
                   if [ $? -ne 0 ]; then
                        echo "[$(date +'%F %T')]: $self use nc connect to $ip udp port $u_port failed."
                   else
                        echo "[$(date +'%F %T')]: $self use nc connect to $ip udp port $u_port success."
                   fi
              done
         fi
    done
          
    echo
}

icmp_probe(){
    for ip in $(echo $cluster_ip | tr ',' ' '); do
        if [ "$ip" != "$self" ]; then
            echo "[$(date +'%F %T')]: ping remote $ip status:"
            echo "##########################################################"
            ping -W 5 -c 8 $ip
            echo
        fi
    done
    echo
}

main(){
    nc_probe
    icmp_probe
    exec 1>&7 7>&-
    if [ $(du -b /tmp/network-monitor.txt | awk '{print $1}') -gt 1073741824 ]; then
        truncate -s 0 /tmp/network-monitor.txt
    fi
}

main
