#!/bin/bash

source "$(dirname "$0")/../../../scripts/t2utils.sh"

"$SHOME/spm" "$SHOME/../macdb/macaddress.txt" > a.txt
"$SHOME/spp" "$SHOME/../macdb/iab.csv" >> a.txt
"$SHOME/spp" "$SHOME/../macdb/oui.csv" >> a.txt
"$SHOME/spp" "$SHOME/../macdb/oui36.csv" >> a.txt
"$SHOME/spp" "$SHOME/../macdb/cid.csv" >> a.txt
"$SHOME/spp" "$SHOME/../macdb/mam.csv" >> a.txt

sort -k1,1 -k2,2 a.txt | uniq | awk -M -F"\t" 'BEGIN{m=0xffffffffffffffff; s = 0xf;} 
!/^#/{ OFS="\t";
    a = strtonum($1);
    b = or(and(rshift(strtonum(m),$2),0xffffffffffff0000),a);
    if (a != s) {
	gsub(/[,.]/,"",$0);
	gsub(/[ ]+$/,"",$4);
        print $1,$2,"0",$3","$5,$4","$5;
        printf "0x%016X\t%d\t1\t%s,%s\t%s,%s\n", b,$2,$3,$5,$4,$5;
        s = a;
    } 
}' > "$SHOME/../macEthlbl_HL.txt"
cat "$SHOME/../macdb/macEthlblP.txt" >> "$SHOME/../macEthlbl_HL.txt"
sed -i '1s/^/#macEType\tmask\tbef\tshortCorp\tcorporation\n/' "$SHOME/../macEthlbl_HL.txt"

sort -k1,1 -k2,2 "$SHOME/../macEthlbl_HL.txt" | awk -F"\t" -M 'BEGIN{i = 0;G[0] = 0;t = 0;l=0;}
 !/^#/{ 
    OFS = "\t";
    c = and(strtonum($1),0xffffffffffff0000);
    e = and(strtonum($1),0xffff);
    if (c != a) {
        if (j > 1) {
	    for (k = 1; k <= j; k++) {
		split(A[k], B, "\t");
		if (e) print B[1], B[2], B[3], or(lshift(b,1), B[4]), B[5], B[6];
		else {
		    print A[k];
		}
	    }
	} else if (j == 1) print A[1];
	j = 0;
	a = strtonum(c);
    }
    i++;
    if ($2 == 48) t = G[l]; 
    else if (and(strtonum($3), 1) == 0) {t = G[l];G[++l] = i;}
    else t = G[--l];
    A[++j] = $1"\t"$2"\t"t"\t"$3"\t"$4"\t"$5;
    b = i;
 } END{
    if (j > 1) {
        for (k = 1; k <= j; k++) {
            split(A[k], B, "\t");
            print B[1], B[2], B[3], or(lshift(b,1), B[4]), B[5], B[6];
        }
    } else if (j == 1) print A[1];
 }' > "$SHOME/../macEthlbl_HLP.txt"

"$SHOME/mbm" "$SHOME/../macEthlbl_HLP.txt" "$SHOME/../macEthlbl_HLP.bin"

rm a.txt
