#!/usr/bin/env bash

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

usage() {
    echo "Usage:"
    echo "    $SNAME [OPTION...]"
    echo
    echo "Optional arguments:"
    echo "    -h, --help        Show this help, then exit"
}

if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
    usage
    exit 0
fi

MACDB_HOME="$($READLINK -f "$SHOME/../macdb")"
if [ ! -d "$MACDB_HOME" ]; then
    printerr "Directory '$MACDB_HOME' does not exist"
    exit 1
elif [ ! -f "$MACDB_HOME/macEthlblP.txt" ]; then
    printerr "File '$MACDB_HOME/macEthlblP.txt' does not exist"
    exit 1
fi

"$SHOME/spm" "$MACDB_HOME/macaddress.txt" >  a.txt || exit 1
"$SHOME/spp" "$MACDB_HOME/iab.csv"        >> a.txt || exit 1
"$SHOME/spp" "$MACDB_HOME/oui.csv"        >> a.txt || exit 1
"$SHOME/spp" "$MACDB_HOME/oui36.csv"      >> a.txt || exit 1
"$SHOME/spp" "$MACDB_HOME/cid.csv"        >> a.txt || exit 1
"$SHOME/spp" "$MACDB_HOME/mam.csv"        >> a.txt || exit 1

sort -k1,1 -k2,2 a.txt | uniq | AWKF -M '
BEGIN {
    m = 0xffffffffffffffff
    s = 0xf
}
!/^#/ {
    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" | AWKF -M '
BEGIN {
    i = 0
    G[0] = 0
    t = 0
    l=0
}
!/^#/ {
    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"

if [ ! -f "$SHOME/mbm" ]; then
    make -C "$SHOME" mbm || exit 1
fi

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

rm a.txt
