#!/bin/bash


usage () {
   echo "Usage: goData.sh [dataFile] [mode]"
   echo "        dataFile: ping output file"
   echo "        mode:   mode 1 produces single RTT data column, mode 2 produces two columns :timestamp RTT "
   echo "  Example:   ./goData.sh ping1.dat 1 > RTT1.dat "
}

INTEGER_REGEXP='^[1-9][0-9]*$'
MODE_REGEXP='^(1|2)$'


# ensure 3 args were passed
if (( $# != 2 )) ; then
   echo "[ERROR] missing operand"
   usage
   exit -1
fi

myFile="$1"
mode="$2"

# ensure mode is either 1 or 2
if ! [[ "$mode" =~ $MODE_REGEXP ]] ; then
   echo "[ERROR] mode must be either 1 or 2"
   usage
   exit -1
fi

#[1504138864.182816] 64 bytes from 202.58.60.194: icmp_seq=2 ttl=237 time=241 ms
#Use grep to search each line for strings like ...time=237", pass what match to awk to print the second field
if [[ "$mode" == 1 ]] ; then
  tail -n +2 $myFile | head -n -3 | grep -o "time=[0-9]*[.]*[0-9]*"  | awk 'BEGIN {FS = "="}{printf("%f\n",$2)}'
fi

#[1504138864.182816] 64 bytes from 202.58.60.194: icmp_seq=2 ttl=237 time=241 ms
#Instead of grep, we use sed to find and replace three strings for an empty string- 
#  The strings:  open and close brackets surrounding the timestamp, and the 'time='. 
if [[ "$mode" == 2 ]] ; then
#  tail -n +2 $myFile | head -n -4 | sed 's/\[//g' | sed 's/\]//g' | sed 's/time=//g' | awk '{printf("%f %d \n",$1, $8)}'
  tail -n +2 $myFile | head -n -4 | sed 's/\[//g;s/\]//g;s/time=//g' | awk '{printf("%f %f \n",$1, $8)}'
fi



