#!/bin/bash

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

usage() {
    echo "Usage:"
    echo "    $SNAME <subfile.txt>"
}

while [ $# -ne 0 ]; do
    case "$1" in
        -h|-\?|--help) usage; exit 0;;
        *)
            if [ ! -f "$1" ]; then
                abort_option_unknown "$1"
            fi
            FILE="$1"
            ;;
    esac
    shift
done

if [ ! -f "$FILE" ]; then
    abort_required_file
fi

make -C utils utils_v6

V="$($AWK -F'\t' 'NR == 1 { print $2, $3; exit }' "$FILE")"
VER="$($AWK '{ print $1 }' <<< "$V")"
REV="$($AWK '{ print $2 }' <<< "$V")"
printinf "Subnet version $VER revision $REV"

k="$($AWK -F'.' -v OFS='.' '{ NF--; print }' <<< "$FILE")"
N="${k}_HL.txt"
F="${k}_HLP.txt"
B="${k}_HLP.bin"

# check subnet version supported by T2
T2V=$(perl -nle 'print $1 if /^#define\s+SUBVER\s+(\d+).*$/' src/subnetHL.h)
if [ "$VER" != "$T2V" ]; then
    printerr "Subnetfile '$FILE' version $VER not supported by Tranalyzer."
    printinf "Please update and ./autogen.sh -f"
    exit 1
fi

SUBRNG=$(perl -nle 'print $1 if /^#define\s+SUBRNG\s+(\d+).*$/' src/utils.h)

$AWK -F'\t' -v SUBRNG=$SUBRNG '
    ARGIND == 1 {
        a[$1] = $2
        next
    }
    ARGIND == 2 {
        b[$1] = $2
        next
    }
    !/^#/ {
        if (split($1, A, "/") > 1) {
            if (strtonum(A[2]) > 128) next
            if ($15 == "--") {
                $15 = 666
                $16 = 666
            }
	    c = or(strtonum(a[$11]), strtonum(b[$5]))
            printf "%s\t-\t%03d\t0x%08x\t%f\t%f\t%f\t%s\t%s\n", A[1], A[2], c, $4, $15, $14, $11, $5
        } else if (SUBRNG > 0 && $1 == "-") {
	    split($2, B, "-");
            printf "%s\t%s\t%03d\t0x%08x\t%f\t%f\t%f\t%s\t%s\n", B[1], B[2], 0, c, $4, $15, $14, $11, $5
	}
    }' ./utils/cntrycd.txt ./utils/who6.txt "$FILE" | ./utils/ext6 > "$N"

sort -t$'\t' -k1,1 -k2,2 "$N" | uniq | ./utils/nett6 | ./utils/vect6 > "$F"

./utils/sbm6 "$F" "$B" "$VER" "$REV"
