#! /usr/bin/env python

from __future__ import print_function
import os, sys
import re
#import argparse
#import collections
import fileinput
#import glob


# I often save the debug output, enabled with the -d command line
# option to p4pktgen, to a file, and then pick through selected
# details if something looks wrong.  For P4 programs with dozens or
# hundreds of paths, this program can be used to summarize the cases
# run a bit.


num_errors = 0
num_packets_generated = 0

packet_generated = None

for line in fileinput.input():
    line = line.rstrip()
    match = re.search(r"^(DEBUG|INFO): (packet|payload)\s+\(\d+ bytes\)\s+(\S+)$", line)
    if match:
        packet_generated = match.group(3)
        continue
    match = re.search(r"^INFO: END\s+(\d+)\s(.*)$", line)
    if not match:
        continue
    test_id = int(match.group(1))
    rest_of_line = match.group(2)
    match = re.search(r"^(.*) complete_path (True|False) (TestPathResult.)?(\S+):(.*)$", rest_of_line)
    if not match:
        print("ERROR: Unexpected contents for 'INFO: END' line:")
        print("ERROR: %s" % (line))
        num_errors += 1
        packet_generated = None
        continue
    complete_path = match.group(2)
    result_type = match.group(4)
    rest_of_line = match.group(5)
    if complete_path == 'True':
        cpath = 'T'
    elif complete_path == 'False':
        cpath = 'F'
    else:
        raise ValueError('weird internal error')

    if result_type not in ['None', 'SUCCESS', 'NO_PACKET_FOUND', 'TEST_FAILED', 'UNINITIALIZED_READ', 'INVALID_HEADER_WRITE']:
        print("ERROR: Unexpected result_type '%s'" % (result_type))
        print("ERROR: %s" % (line))
        num_errors += 1
        packet_generated = None
        continue
    if result_type in ['SUCCESS', 'TEST_FAILED']:
        num_packets_generated += 1
        pkt_id = str(num_packets_generated)
    else:
        # No packet generated by p4pktgen for the other cases
        pkt_id = 'N/A'
    if packet_generated is None:
        print("packet None")
    else:
        print("packet (%d bytes) %s" % (len(packet_generated) / 2,
                                        packet_generated))
    print("pkt %s case %d cpath %s res %s details %s"
          "" % (pkt_id, test_id, cpath, result_type,
                rest_of_line))


if num_errors != 0:
    sys.exit(1)
