#!/usr/bin/env bash

ip=$1
port=$2
use_crc=$3

if [ $# -ne 3 ]; then
  echo "Enter 2 args: read_ptpg_diags <IP address of iface connected to PTPG> <port number> <0: DISCARD CRC / 1: USE CRC>."
  exit 1
fi

if ! command -v socat &> /dev/null
then
  echo "socat not found. Please install socat."
  exit
fi

PROTOC=$(mktemp)

function cleanup {
  clear
  rm -f $PROTOC
  echo "Caught Signal: Terminating ..."
  exit
}
# If user terminates program, clear the terminal and reset it
trap cleanup SIGINT SIGTERM

bazel run --script_path=$PROTOC @protobuf_archive_py3//:protoc


clear

while :
do

if [ $use_crc -eq 1 ]; then
# bash variables cannot store binary data. We need to encode as base64 type and store and then
# decode and pipe to a command in order to use.
  proto=$(socat UDP4-RECVFROM:$port,ip-add-membership=239.195.1.2:$ip,reuseaddr - | base64)
  # capture the CRC into a var
  crc=$(od -An -t x4 <(echo  "$proto" | base64 -d | tail --bytes=4 ))
  computed_crc=$(crc32 <(echo -n "$proto" | base64 -d | head -c -4))

  printf "Computed CRC  = %s\n" $computed_crc
  printf "Extracted CRC = %s\n" $crc

  if [ $computed_crc != $crc ]; then
    echo "CRC MISMATCH !! "
  fi

  echo "$proto" | base64 -d | head -c -4 | \
  $PROTOC --decode=zoox.common.proto.PtpGatewayStatus -I$ZOOX_WORKSPACE_ROOT \
  $ZOOX_WORKSPACE_ROOT/vehicle/common/proto/ptpg_diagnostics.proto | pr -4 -t -J --sep-string=+ | column -t -s '+'
else
  socat UDP4-RECVFROM:$port,ip-add-membership=239.195.1.2:$ip,reuseaddr - | head -c -4 | \
  $PROTOC --decode=zoox.common.proto.PtpGatewayStatus -I$ZOOX_WORKSPACE_ROOT \
  $ZOOX_WORKSPACE_ROOT/vehicle/common/proto/ptpg_diagnostics.proto | pr -4 -t -J --sep-string=+ | column -t -s '+'
fi
tput cup 0 0

done
