#!/bin/bash
#  Ping-Statistik mit geringem Aufwand (Vergleich zu smokeping)
#  erfordert Gnuplot, ping (iputils)
#
usage() {
    echo "usage:"
    echo "  locally  (root): ping -s size -i interval -c count target > result-file"
    echo "  remotely (root): ssh root@hostname \"ping -s size -i interval -c count target\" > result-file"
    echo " then postprocess:    pingstat.sh result-file"
    exit 0
}

[ "$1" = "-h" ] && usage

PINGAUSGABE=$1
TimeStamp=$(ls -l --time-style=full-iso  "$PINGAUSGABE" |awk '{printf"%sT%s\n",$6,$7}')
PingZiel=$(head -1 "$PINGAUSGABE"|awk '{ print $2}')
Psize=$(head -1 "$PINGAUSGABE"|awk '{ print $4}')
RESULT=$(grep received "$PINGAUSGABE")
RTT=$(grep rtt "$PINGAUSGABE")
echo "Datei: $TimeStamp Ziel: $PingZiel"

STATDATEI=$PINGAUSGABE.stats
CSV1=$PINGAUSGABE.csv
CSV2=$PINGAUSGABE-missing
TMPPNG1=$PINGAUSGABE-zeit.png
TMPPNG2=$PINGAUSGABE-stat.png
#TMPPNG3=$PINGAUSGABE-temp3.png
GnuPlotFile=$PINGAUSGABE.p
#------------------------------------------
CreateGnuplotFile() {
#  PDF-Datei nachbearbeiten, dazu Datei vornbereiten…
cat > "$1" <<EOF
title1='Pingzeit to $PingZiel, ($Psize b). $INTV s, $RESULT'
title2='Pingstatistik $BREITE, $RTT, $TimeStamp'
datum='$TimeStamp'
datei1='$CSV1'
datei2='$CSV2'
ausgabe1='$TMPPNG1'
ausgabe2='$TMPPNG2'
miss='$MISS'
set terminal png size 1200,800
EOF
cat /usr/lib/pingstat/pingstat.p >> "$GnuPlotFile"
}

run_test() {
    echo "Teste $1"
    if [ -n "$REMOTEHOST" ]
    then ssh "root@$REMOTEHOST" "ping -n -s \"$PSIZE\" -i \"$INTV\" -c \"$ANZAHL\" \"$1\" " >"$2"
    else ping -n -s "$PSIZE" -i "$INTV" -c "$ANZAHL" "$ZIEL" >"$2"
    fi
}
get_missing()  {
    YYY=0
    grep "time=" "$1"|awk '{print $6}'|cut -d'=' -f2|sort -n|while read -r XXX  # grep sequence number
    do
    #	echo $XXX : $YYY
    	YYY=$((YYY+1))
    	{
    	while [ $YYY -lt "$XXX" ]
    	do
    		echo "$YYY"
    		YYY=$((YYY+1))
    	done } >"$2"
    done
}
#
##echo "Pingtest von $QUELLHOST auf $ZIEL mit $PSIZE × $ANZAHL pings im Intervall $INTV"
##run_test  "$ZIEL"   "$PINGAUSGABE"
#
pingresult_to_csv() {
#  64 bytes from fritz.box (192.168.178.1): icmp_seq=1 ttl=64 time=1.24 ms
#  1    2    3       4             5            6        7        8      9
#                                                    |             |
    awk '{printf "%s,%s\n",$6,$8}' "$1" |sed -e "s/time=//g" -e "s/icmp_[sr]eq=//g" |head -n -4|tail -n +2 >"$2"
}

count_missing_lines() {
    MISS=$(awk '{x++}END{ print x}' "$1")
    [ -z "$MISS" ] && MISS=0
}
pingresult_to_csv "$PINGAUSGABE" "$CSV1"
get_missing "$PINGAUSGABE" "$CSV2"
count_missing_lines "$CSV2"
CreateGnuplotFile "$GnuPlotFile"
#
gnuplot "$GnuPlotFile" 2>"$STATDATEI" || exit 1
