#!/usr/bin/env bash

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

usage() {
    echo "Usage:"
    echo "    $SNAME [OPTION...] file_bgp.txt"
    echo
    echo "Optional arguments:"
    echo "    -t            keep the timestamp"
    echo
    echo "    -p            generate the plots"
    echo
    echo "    -d            directed graph"
    echo "    -s            max one edge between nodes"
    echo "    -u            no links to self node"
    echo
    echo "    -l            label edges with the flowIndex"
    echo "    -n            color nodes"
    echo "    -e            color edges"
    echo
    echo "    -f FMT        output format (gif, png, ps, svg, svgz) [default: '$FORMAT']"
    echo "    -o DIR        output folder [default: '$OUTFOLDER']"
    echo
    echo "    -y            do not ask for confirmation before executing an action"
    echo
    echo "    -h, --help    Show this help, then exit"
}

cleanup() {
    local ret=$1
    exit $ret
}

# Configuration options
TSTAMP=0      # 0: ignore timestamps, 1: include timestamps
PLOT=0        # 0: no plots, 1: plots
DGRAPH=0      # 0: undirected graph, 1: directed graph
LABEL=0       # 0: no labels for edges, 1: flow index
COLORE=0      # 0: no color for edges, 1: color
COLORN=0      # 0: no color for nodes, 1: color
UNIQ=0        # 0: no links to self, 1: links to self
STRICT=""     # strict: max one edge between nodes
FORMAT="png"  # Output format: png, ps, svg, svgz, fix, gif, imag, cmapx
OUTFOLDER="." # output folder (default to current directory)

while [ $# -gt 0 ]; do
    case "$1" in
        -p|--plot) PLOT=1;;
        -t|--with-timestamps) TSTAMP=1;;
        -d|--digraph) DGRAPH=1;;
        -l|--label-edges) LABEL=1;;
        -e|--color-edges) COLORE=1;;
        -n|--color-nodes) COLORN=1;;
        -u|--no-links-to-self) UNIQ=1;;
        -s|--strict) STRICT="strict ";;
        -y|--yes) YES="yes";;
        -f|--format)
            validate_next_arg "$1" "$2"
            FORMAT="$2"
            shift
            ;;
        -o|--output-folder)
            validate_next_dir "$1" "$2"
            OUTFOLDER="$2"
            shift
            ;;
        -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

check_dependency "dot" "graphviz"

# Setup signal handler
trap "trap - SIGTERM && exit 1" HUP INT QUIT TERM
trap "exit \$?" EXIT

NAME="$(basename "$FILE" .txt)"
OUT="${OUTFOLDER}/${NAME}_s.txt"
MPATH="${OUTFOLDER}/${NAME}_mpath.txt" # all networks with more than one path
MOASFILE="${OUTFOLDER}/${NAME}_moas.txt" # all networks with multiple origins
CONFFILE="${OUTFOLDER}/${NAME}_conf.txt" # possible configuration errors (AS prepended N times, followed by AS number N)
ASNCNF="$(dirname "$($READLINK -f "$0")")/asn2cn.txt"

# test whether the file has the correct format
RES="$(AWK -F'\t' '
    NR == 1 {
        for (i = 1; i <= NF; i++) {
            if ($i == "ASPath") {
                print $i
                exit
            }
        }
        exit
    }' "$FILE")"
if [ -z "$RES" ]; then
    printerr "File '$FILE' is not valid: column 'ASPath' not found"
    exit 1
fi

# test whether output file already exists
if [ -f "$OUT" ]; then
    printwrn "Output file '$OUT' already exists..."
    printf "Overwrite (Y/n)? "
    if [ -z "$YES" ]; then
        read ans
    else
        ans="yes"
        echo "$ans"
    fi
    case "$ans" in
        n|N) printf "Aborting\n"; exit;;
    esac
fi

# Split NLRI and add AS Path Countries and AS Path Continents
printf "Generating '$OUT'... "
AWKF -v asn2cnfile="$ASNCNF" -v addtime="$TSTAMP" '
    BEGIN {
        while ((getline l < asn2cnfile) > 0) {
            split(l, as, "\t");
            as2cn[as[1],1] = as[2]; # Country
            as2cn[as[1],2] = as[3]; # Continent
        }
    }
    NR == 1 {
        for (i = 1; i <= NF; i++) {
            if ($i == "AS") asc = i;
            else if ($i == "ASPath") aspath = i;
            else if ($i == "ASPathLen") aspathlen = i;
            else if ($i == "WithdrawnRoutes") wdrawn = i;
            else if ($i == "flowIndex") flowInd = i;
            else if ($i == "Timestamp") tstamp = i;
        }
        if (asc == 0 || aspath == 0 || aspathlen == 0 || wdrawn == 0 || flowInd == 0) {
            print "One of the AS/ASPath/ASPathLen/WithdrawnRoutes/flowIndex columns could not be found"
            exit 1
        }
        if (addtime && tstamp == 0) {
            print "Timestamp column could not be found"
            exit 1
        }
        next
    }
    function asn2cn(asn,country) {
        cn = asn
        sub(/^[^[:digit:]]*/, "", asn)
        sub(/[^[:digit:]]*$/, "", asn)
        if (as2cn[asn,country+1]) newlabel = as2cn[asn,country+1]
        else newlabel = "ZZ"
        sub(/[[:digit:]]+/, newlabel, cn)
        return cn
    }
    NR > 1 {
        if ($wdrawn) {
            nwd = split($wdrawn, w, ";")
            for (i = 1; i <= nwd; i++) {
                printf "W\t%s\t%s", w[i], $asc
                # add a tab for countries and continents
                for (j = asc; j < wdrawn+1; j++) {
                    printf "\t";
                }
                for (j = flowInd; j < NF; j++) {
                   printf "\t%s", $j
                }
                if (addtime) printf "\t%s", $tstamp
                printf "\n"
            }
        }
        # Split networks
        na = split($1, a, ";");
        for (i = 1; i <= na; i++) {
            $1 = a[i];
            printf "A\t"
            for (j = 1; j < aspath; j++) printf "%s\t", $j;
            printf "%s\t%s\t", $aspathlen, $aspath;
            nb = split($aspath, b, ";");
            # Countries
            for (j = 1; j < nb; j++) {
                printf "%s;", asn2cn(b[j],1);
            }
            printf "%s\t", asn2cn(b[j],1);
            # Continents
            for (j = 1; j < nb; j++) {
                printf "%s;", asn2cn(b[j]);
            }
            printf "%s", asn2cn(b[j]);
            for (j = aspathlen+1; j < NF; j++) {
                if (j != wdrawn) {
                    printf "\t%s", $j;
                }
            }
            if (addtime) printf "\t%s", $tstamp
            printf "\n"
        }
    }' "$FILE" > "$OUT"
printok "OK"

# Sort the file
printf "Sorting '$OUT'... "
sort -Vu -o "$OUT" "$OUT"
printok "OK"

# Prepend the header
HDR="$(AWKF -v addtime="$TSTAMP" '
    NR == 1 {
        printf "%%AW\tNLRI\t"
        for (i = 2; $i != "ASPath"; i++) printf "%s\t", $i;
        printf "%s\t%s\tASPathCountries\tASPathContinents", $(i+1), $i; # ASPathLen, ASPath
        for (i += 2; i < NF; i++) {
            if ($i != "WithdrawnRoutes") { # Do not print WithdrawnRoutes
                printf "\t%s", $i;
            }
        }
        if (addtime) printf "\t%s", $i; # timestamp
        printf "\n";
        exit
    }' "$FILE")"
$SED -i "1s/^/$HDR\n/" "$OUT"

printf "Generating '$MPATH'... "
# Compute some statistics
AWKF '
    NR == 1 {
        for (i = 1; i <= NF; i++) {
            if ($i == "NLRI") NLRI = i
            else if ($i ==  "ASPath") ASPath = i
            else if ($i ==  "ASPathLen") ASPathLen = i
        }
        if (NLRI == 0 || ASPath == 0 || ASPathLen == 0) {
            print "One of NLRI, ASPath or ASPathLen column could not be found"
            exit
        }
        next
    }
    /^A/ { # ignore withdrawn routes
        print $NLRI, $ASPath, $ASPathLen
    }' "$OUT" | sort -u | AWKF -v moasfile="$MOASFILE" '
    {
        a[$1]++

        if (!($1 in min) || $3 < min[$1]) min[$1] = $3
        if ($3 > max[$1]) max[$1] = $3
        mode[$1][$3]++

        _delta   = $3 - m1[$1]
        _delta_n = _delta / a[$1]
        _term1   = _delta * _delta_n * (a[$1] - 1.0)

        m1[$1] += _delta_n
        m2[$1] += _term1
    }
    END {
        while ((getline l < moasfile) > 0) {
            split(l, m, "\t");
            moas[m[1] "/" m[2]] = "MOAS"
        }

        for (i in a) {
            if (a[i] > 1) {
                _maxmode = 0
                _mode = 0
                for (j in mode[i]) {
                    if (mode[i][j] > _maxmode) _mode = j
                }
                print i, a[i], min[i], max[i], max[i] - min[i], m1[i], (min[i]+max[i])/2.0, (a[i] <= 1) ? NAN : sqrt(m2[i] / (a[i] - 1)), _mode, moas[i]
            }
        }
    }' | sort -t$'\t' -nrk2 > "$MPATH"
$SED -i "1s/^/%Network\tNumberOfDifferentPaths\tMinPathLen\tMaxPathLen\tRangePathLen\tMeanPathLen\tMedianPathLen\tStdDevPathLen\tModePathLen\tMOAS\n/" "$MPATH"
printok "OK"

# Extract possible configuration errors
printf "Generating '$CONFFILE'... "
AWKF '
    NR == 1 {
        for (i = 1; i <= NF; i++) {
            if ($i ==  "ASPath") ASPath = i
            else if ($i == "MaxNPrepAS") MaxNPrepAS = i
        }
        if (ASPath == 0 || MaxNPrepAS == 0) {
            print "One of ASPath or MaxNPrepAS column could not be found"
            exit
        }
        print
        next
    }
    $MaxNPrepAS > 0 {
        n = split($ASPath, asp, ";")
        prevas = 0
        prevcnt = 0
        for (i = 1; i <= n; i++) {
            gsub("[{}]", "", asp[i])
            if (prevas == asp[i]) {
                cnt++
            } else {
                cnt = 1
            }
            if (asp[i] == ($MaxNPrepAS+1) && prevas && prevcnt == asp[i]) {
                # possible configuration error (AS prepended N times, followed by AS number N)
                print
                next
            }
            prevas = asp[i]
            prevcnt = cnt
        }
    }' "$OUT" > "$CONFFILE"
printok "OK"

if [ $PLOT -eq 0 ]; then
    exit 0
fi

# Plot AS paths between AS numbers and countries
# TODO not working for AS_SETS, e.g., {as1;as2}
for i in as cn cont; do
    printf "Generating '$i' plot... "
    DOUT="${OUTFOLDER}/${NAME}_${i}.dot"
    if [ $DGRAPH -eq 1 ]; then
        GRAPH="digraph"
    else
        GRAPH="graph"
    fi
    echo "$STRICT$GRAPH {" > "$DOUT"
    printf "\tnode [style=filled]\n" >> "$DOUT"
    AWK -v m="$i" -v dg="$DGRAPH" -v label="$LABEL" \
        -v colorE="$COLORE" -v colorN="$COLORN" -v uniq="$UNIQ" '
        NR == 1 {
            for (i = 1; i <= NF; i++) {
                if ($i == "ASPath") as = i;
                else if ($i == "ASPathCountries") cn = i;
                else if ($i == "ASPathContinents") cont = i;
                else if ($i == "flowIndex") flowIndex = i;
            }
            if (!as) { print "Column ASPath could not be found"; exit }
            if (!cn) { print "Column ASPathCountries could not be found"; exit }
            if (!cont) { print "Column ASPathContinents could not be found"; exit }
            if (!flowIndex) { print "Column flowIndex could not be found"; exit }
        }
        NR > 1 {
            if ($as ~ /.*[\[{].*;.*[\]}].*/) next # TODO ignore sets with multiple AS for now
            na = split($as, a, ";");
            split($cn, c, ";");
            split($cont, k, ";");
            for (i = 1; i <= na; i++) {
                if (a[i] ~ /^\{[[:digit:]]+\}$/) { # set with a single as: {as}->as
                    sub(/^\{/, "", a[i])
                    sub(/\}$/, "", a[i])
                    sub(/^\{/, "", c[i])
                    sub(/\}$/, "", c[i])
                    sub(/^\{/, "", k[i])
                    sub(/\}$/, "", k[i])
                }
                if (colorN) {
                    if (m == "as") {
                        switch (c[i]) {
                            case "CH": color = "red"; break;
                            case "US": color = "dodgerblue"; break;
                            case "AR": color = "yellow"; break;
                            case "NP": color = "green"; break;
                            case "NG": color = "magenta"; break;
                            case "ID": color = "orchid"; break;
                            case "HK": color = "powderblue"; break;
                            case "DE": color = "orange2"; break;
                            case "GB": color = "khaki1"; break;
                            case "ZA": color = "ivory2"; break;
                            case "IN": color = "seagreen1"; break;
                            case "RS": color = "seashell1"; break;
                            case "PL": color = "sienna1"; break;
                            case "MU": color = "plum1"; break;
                            case "IT": color = "skyblue1"; break;
                            case "RU": color = "turquoise1"; break;
                            case "BR": color = "tan3"; break;
                            case "BW": color = "palegreen1"; break;
                            default:   color = "white"; break;
                        }
                    } else {
                        switch (k[i]) {
                            case "ripencc": color = "firebrick1"; break; # Europe
                            case "arin"   : color = "dodgerblue"; break; # US
                            case "apnic"  : color = "yellow";     break; # Asia
                            case "afrinic": color = "green";      break; # Africa
                            default       : color = "white";      break;
                        }
                    }
                } else {
                    color = "white";
                }
                if (m == "as") printf "\t%s[label=\"%d\\n%s\\n%s\", fillcolor=%s]\n", a[i], a[i], c[i], k[i], color;
                else if (m == "cn") printf "\t%s[label=\"%s\\n%s\", fillcolor=%s]\n", c[i], c[i], k[i], color;
                else printf "\t%s[label=\"%s\", fillcolor=%s]\n", k[i], k[i], color;
            }

            if (colorE) {
                cstr = "red;black;blue;yellow;green;magenta;orchid;powderblue;orange2;khaki1;ivory2;seagreen1;seashell1;sienna1;plum1;skyblue1;turquoise1;tan3;palegreen1";
                nc = split(cstr, colors, ";");
            }
            if (m == "as") printf "\t%s", a[1];
            else if (m == "cn") printf "\t%s", c[1];
            else printf "\t%s", k[1];
            plen = 0
            for (i = 2; i <= na; i++) {
                if (uniq && ((m == "as" && a[i] == a[i-1]) || (m == "cn" && c[i] == c[i-1]) || (m == "cont" && k[i] == k[i-1])))
                    continue
                plen++
                if (m == "as") printf " %s %s", dg ? "->" : "--", a[i];
                else if (m == "cn") printf " %s %s", dg ? "->" : "--", c[i];
                else printf " %s %s", dg ? "->" : "--", k[i];
            }
            if (plen > 0 && (label || colorE)) {
                printf "["
                if (label) printf "label=%s", $flowIndex;
                if (label && colorE) printf ","
                if (colorE) printf "color=%s", colors[1 + ($flowIndex % nc)];
                printf "]"
            }
            printf "\n";
        }' "$OUT" | sort -u >> "$DOUT"
    echo "}" >> "$DOUT"
    dot -T"$FORMAT" "$DOUT" > "${OUTFOLDER}/${NAME}_${i}.${FORMAT}"
    if [ $? -eq 0 ]; then
        printok "OK"
    else
        printerr "FAILED"
    fi
done
