#!/bin/bash

help()
{
    echo "Usage: loxilb_dp_tool[ -d | --dump-latency]
               [ -h | --help  ]"
    exit 2
}

SHORT=d,h
LONG=dump-latency,help
OPTS=$(getopt -a -n loxilb_dp_tool --options $SHORT --longoptions $LONG -- "$@")

VALID_ARGUMENTS=$# # Returns the count of arguments that are in short or long options

if [ "$VALID_ARGUMENTS" -eq 0 ]; then
  help
fi

eval set -- "$OPTS"

dump_latency() {
  ncpu=`nproc`
  ccpu=0
  total=0
  interval=0
  sudo bpftool map dump pinned /opt/loxilb/dp/bpf/pplat_map | grep packets | sed 's/^[ \t]*//;s/[ \t]*$//' | cut -d ' ' -f 2 > pps
  input="./pps"
  while IFS= read -r line
  do
    if [[ $ccpu -ge ${ncpu} ]]; then
      ccpu=0
      if [[ ${total} != 0 ]]; then
         factor=1
         intact=$(( ${interval} + 1 ))
         time=$(( ${intact} * ${factor} ))
         #echo "${time}us $total"
         printf '%10sus %10s packets\n' "${time}" "$total"
      fi
      #echo "HeLLO"
      interval=$(( interval + 1 ))
      total=0
    fi
    #echo "$ccpu $line"
    if [[ ${line} != 0 ]]; then
      total=$(( ${total} + ${line} ))
    fi
    ccpu=$(( ${ccpu} + 1))
  done < "$input"
  rm -f pps
}

while :
do
  case "$1" in
    -d | --dump-latency)
      dump_latency
      shift 1
      ;;
    -h | --help)
      help
      ;;
    --)
      shift;
      break
      ;;
    *)
      echo "Unexpected option: $1"
      help
      ;;
  esac
done


