#! /usr/bin/env bash
#
# A diff canonifier that sorts conn.log service field (it's derived from a set
# type and output may be unstable)

awk '
BEGIN {
    FS="\t";
    OFS="\t";
    process = 0;
    }

function bubble_sort(arr, len,    keep_going, i, tmp)
    {
    keep_going = 1;

    while ( keep_going == 1 )
        {
        keep_going = 0;

        for ( i = 1; i <= len - 1; ++i )
            {
            if ( arr[i] > arr[i + 1] )
                {
                tmp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = tmp;
                keep_going = 1;
                }
            }
        }

    return len;
    }

$1 == "#path" && $2 == "conn" {
    process = 1;
    }

/^[^#]/ {
    if ( process && column1 > 0 && $column1 != "-" )
        {
        n = split($column1, set_contents, ",");
        n = bubble_sort(set_contents, n);
        sorted_field = set_contents[1];

        for ( e = 2; e <= n; ++e )
            sorted_field = sorted_field "," set_contents[e];

        $column1 = sorted_field;
        }
    }

/^#fields/ {
    for ( i = 2; i <= NF; ++i ) {
        if ( $i == "service" )
            column1 = i - 1;
        }
    }

{ print }
'
