#!/bin/bash

red=$'\e[1;31m'
grn=$'\e[1;32m'
yel=$'\e[1;33m'
blu=$'\e[1;34m'
mag=$'\e[1;35m'
cyn=$'\e[1;36m'
end=$'\e[0m'

if [ -f result.txt ]; then
    /bin/rm -f result.txt
fi

  /bin/rm -f online_ips.txt > /dev/null
  /bin/rm -f offline_ips.txt > /dev/null

#we must give ips.txt as an argument
if [ $# -ne 0 ]; then
	
  while read line 
	do
		ping -q -c 2 $line >> result.txt 

		if [ $? -eq 0 ]; then
 		facts=`grep -E -A1 "${line}.*ping statistics" result.txt | tail -n 1`
 		printf "%s\n" "$line is ${grn}Online${end} with $facts"
	  echo "$line" >> online_ips.txt
 		else
 		facts=`grep -E -A1 "${line}.*ping statistics" result.txt | tail -n 1` 
 		printf "%s\n" "$line is ${red}Offline${end} with $facts"
 		echo "$line" >> offline_ips.txt
		fi	

	done < ips.txt
  echo -e "\n"
  printf "%s\n" "${red}`cat offline_ips.txt 2> /dev/null | sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 | uniq | sed -e 's/^[ \t]*//'` ${end}"
  echo -e "\n\nWe have `cat offline_ips.txt 2> /dev/null | wc -l` IPs which are offline!"
  
  #we test all IPs installed on server 
  else
    . /etc/sysconfig/perl-iptdaemon
        OVPN_COUNT=0
        for line in $(grep IPADDR /etc/sysconfig/network-scripts/ifcfg-$IPTDAEMON_INTERFACE:* | awk -F"=" '{print $2}'); do
            if [ -n "$line" ]; then
                
		ping -q -c 1 $line >> result.txt
                
		if [ $line == 94.156.219.244 -o $line == 94.156.219.241 ]; then
                	facts=`grep -E -A1 "${line}.*ping statistics" result.txt | tail -n 1`
                	printf "%s\n" "$line is ${red}Offline${end} with $facts"
                	echo "$line" >> offline_ips.txt
                fi
                if [ $? -eq 0 ]; then
                	facts=`grep -E -A1 "${line}.*ping statistics" result.txt | tail -n 1`
                	printf "%s\n" "$line is ${grn}Online${end} with $facts"
                	echo "$line" >> online_ips.txt
                else
                	facts=`grep -E -A1 "${line}.*ping statistics" result.txt | tail -n 1`
                	printf "%s\n" "$line is ${red}Offline${end} with $facts"
                	echo "$line" >> offline_ips.txt
                fi

                OVPN_COUNT=$(($OVPN_COUNT+1))
            fi
        done
        
				echo -e "\n"
        printf "%s\n" "${red}`cat offline_ips.txt 2> /dev/null | sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 | uniq | sed -e 's/^[ \t]*//'` ${end}"
				echo -e "\n\nWe have `cat offline_ips.txt 2> /dev/null | wc -l` IPs which are offline!"
fi

