#!/bin/bash
set +x

sampledata=${@:-$(date +"%s")}

calculate()
{
    echo "\rSIGINT caught"
    was_failover=1
    old_timestamp=""
    TIMESTAMPS=/home/armen/testdata/$sampledata/*
    for timestamp  in $TIMESTAMPS
    do
        timestamp=$(basename $timestamp)
        if [[ "$old_timestamp" != "" ]]
        then
            time_diff=$((($timestamp - $old_timestamp)/1000000))
            if [[ $time_diff -ge 50 ]]
            then
                echo "We've got a failover time of $time_diff ms"
                was_failover=0
            fi
        fi
        old_timestamp=$timestamp
    done
    if [ $was_failover -ne 0 ]
    then
       echo "No downtime detected"
    fi
    cleanup
}

cleanup()
{
    rm -rf /home/armen/testdata/$sampledata
}

control_c()
# run if user hits control-c
{
  calculate
  exit $?
}

cleanup

echo "Mounting..."

mkdir -p /home/armen/testdata/$sampledata

echo "Wait 60 sec, then hit CTRL+C"

# trap keyboard interrupt (control-c)
trap control_c SIGINT

# set current date in epoch
while true
do
    epoch=$(date +"%s%N")
    touch /home/armen/testdata/$sampledata/$epoch &
    pid=$!
    if [ $? -eq 0 ];  then
        echo "mountpoint is up (${pid})"
    fi
    wait $pid
    echo "Testing $sampledata..."
done