#!/usr/bin/env python3
# Copyright (c) 2020 Arista Networks, Inc.  All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.

# Use tcpdump to format a packet supplied on the command line
# as a hex string.

from __future__ import absolute_import, division, print_function

import codecs
import struct
import subprocess
import sys
import tempfile

def usage():
   print( "Usage: qtpkt longhexstring" )
   sys.exit( 1 )

if len( sys.argv ) != 2:
   usage()

try:
   decoder = codecs.getdecoder( 'hex_codec' )
   pktData = decoder( sys.argv[ 1 ] )[ 0 ]
except TypeError:
   print( "That did not look like a hex string" )
   usage()

# struct pcap_file_header
# magic, version.version, mbz, mbz, snaplen, DLT_EN10MB
pcap = struct.pack( 'IHHIIII', 0xa1b2c3d4, 2, 4, 0, 0, 65535, 1 )
# struct pcap_sf_pkthdr
# tv_sec, tv_usec, caplen, len
pcap += struct.pack( 'IIII', 0, 0, len( pktData ), len( pktData ) )
pcap += pktData
# Use a temp file.
tempFile = tempfile.NamedTemporaryFile( prefix='qt-pcap-' )
tempFile.write( pcap )
tempFile.flush()
# -t: no timestamp
# -v: verbose
# -e: ethernet too
# -nn: no address or port resolution
subprocess.check_call( [ "tcpdump", "-tvenn", "-r", tempFile.name ] )
