#!/bin/bash
 
# This tool is used to convert qlogs generated by tquic tools from JSON-SEQ
# format to JSON format, and make other changes to be compatible with qvis.
# See https://qvis.quictools.info

# Check whether jq is installed
if ! command -v jq &> /dev/null
then
    echo "Please install jq to use this script."
    echo "See https://jqlang.github.io/jq/download/"
    exit 1
fi

# Check whether a file name is provided
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <qlog_file>"
    echo "Description: convert qlog from JSON-SEQ to JSON format compatible with qvis"
    exit 1
fi

# Check whether the file exists
if [ ! -f "$1" ]; then
    echo "Error: File '$1' not found."
    exit 1
fi

# Convert to JSON format
OUT="$1.qvis.json"
sed 's/^\x1e//' $1 | jq -s '.[1:] as $events | .[0] | .trace.events=$events | .traces=[.trace] | del(.trace) | .qlog_format="JSON"' > $OUT

# Change for backward compatibility
# Note qvis reportedly does not plan to implement qlog 0.4 and will continue
# using 0.3 until a 1.0 RC is specced.
sed -i -e 's/name": "quic:/name": "transport:/' -e 's/"qlog_version": "0.4"/"qlog_version": "0.3"/' $OUT
