#!/bin/bash

# Handler script for protocol buffer view tool.

VALID_ARGS=$(getopt -o hi:j:wm:d --long help,input:,json:,dump,wrap,max-line: -- "$@")
INPUT_FILE=""
OUTPUT_FILE=""
MAX_LINE=0
WRAP=false
DUMP=false
JSON=false
eval set -- "$VALID_ARGS"
EXECUTABLE_ARGS=""

display_help() {
  echo "-i | --input: Binary input file for protobuf radar data"
  echo "-h | --help: Prints this help message"
  echo "-w | --wrap: Wrap lines into new line"
  echo "-m | --max-line: Defines maximum number of moments in one line"
  echo "-d | --dump: Dumps out all the available moment data"
  echo "-j | --json: Dump out a json file of the protobuf data"
}

if [[ $# -eq 1 ]]; then
	display_help
	exit 0
fi

while [ : ]; do
	case "$1" in
    -h | --help)
      display_help
      exit 0
      ;;
    -i | --input)
      INPUT_FILE=$2
      shift 2
      ;;
    -m | --max-line)
      MAX_LINE=$2
      shift 2
      ;;
    -w | --wrap)
      WRAP=true
      shift
      ;;
    -d | --dump)
      DUMP=true
      shift
      ;;
    -j | --json)
      OUTPUT_FILE=$2
      JSON=true
      shift 2
      ;;
    --) shift; 
      break 
      ;;
    esac
done

if [[ $WRAP == true ]]; then
  EXECUTABLE_ARGS="${EXECUTABLE_ARGS} --wrap"
fi

if [[ $DUMP == true ]]; then
  EXECUTABLE_ARGS="${EXECUTABLE_ARGS} --dump"
fi

if [[ $MAX_LINE -ne 0 ]]; then
  EXECUTABLE_ARGS="${EXECUTABLE_ARGS} --max-line ${MAX_LINE}"
fi

if [[ $JSON == true ]]; then
  EXECUTABLE_ARGS="${EXECUTABLE_ARGS} --json ${OUTPUT_FILE}"
fi

# Attempt common-dto first
protox-common-dto --binary-path ${INPUT_FILE} ${EXECUTABLE_ARGS} 2>/dev/null

# If common-dto fails, try input-dto
if [ $? -ne 0 ]; then
    protox-input-dto --binary-path ${INPUT_FILE} ${EXECUTABLE_ARGS} 2>/dev/null
fi

exit 0