#!/usr/bin/env bash

echo "--- runs largish topology and flaps a link between edge/aggregation looking for POD level auto "
echo "    deaggregation ..."
echo

# Copyright (c) 2016-, Juniper Networks, Inc.
# All rights reserved.

set -e

ulimit -n 4096

`which python` --version || {
    echo "install python ..."
    exit 1
}

OF=/tmp/rift.out.$$

echo running as $$ writing out to $OF

# break the link from 104 to 1001 which should lead to disaggregation on 103,102,101 and 1001/1002 recomputing

# -vvv -Nedge_1002 -Cspf
../bin/rift-environ -vv -c topology -u -DD ../topology/3pod2edge4acc3core100pfx.yaml  > $OF 2>&1 << EOF
sleep 1000
bfd down node "agg_104" interface "intf_104_1001-"
bfd down node "edge_1001" interface "intf_1001_104-"
sleep 2000
quit

EOF

# derive all the downtimes

echo

LFT=`grep 'stopping interface' $OF`

echo "$LFT"
echo

echo
cat $OF | ./lib/countfloodcountfilter.sh
cat $OF | ./lib/countfloodretransmits.sh
cat $OF | ./lib/countfloodreductions.sh
echo

echo "--- last RIB transaction timestamps & routing tables for key nodes"
echo

for N in core_1 agg_101 agg_102 agg_103 agg_104 edge_1001 edge_1002 core_2 agg_201 edge_2001 agg_301 edge_3001
do
    echo

    LRT=`python lib/curlies.py "RIB stats for $N" < $OF | python lib/curlies.py " *last_transaction:" | egrep "(secs|msecs)"`
    echo "$N last RIB transaction: " $LRT

    LRR=`python lib/curlies.py "RIB stats for $N" < $OF | python lib/curlies.py " *IPV4: AFRoutingTableStatistics" | egrep "currentprefixes"`
    echo "$N RIB routes: " $LRR

    LST=`python lib/curlies.py "LSDB Stats for $N" < $OF | python lib/curlies.py " *last_southbound"`

    [ -z "$LST" ] || {
        LST=`echo $LST | egrep "(secs|msecs)"`
        echo "$N last southbound prefix/deaggregation: " $LST
    }

    DAP=`python lib/curlies.py "SPO stats for $N" < $OF | egrep " *current_deaggregated_prefixes:"`
    echo "$N deaggregated prefixes: " $DAP

    # derive interface, south and northbound route counts
    IRT=`python lib/curlies.py "RIB routing table for $N" \< \> < $OF | egrep "^i" | wc -l`
    echo "$N v4 interface routes: $IRT"

    NRT=`python lib/curlies.py "RIB routing table for $N" \< \> < $OF | egrep "^n" | wc -l`
    echo "$N v4 northbound routes: $NRT"

    SRT=`python lib/curlies.py "RIB routing table for $N" \< \> < $OF | egrep "^s" | wc -l`
    echo "$N v4 southbound routes: $SRT"

    [ $SRT -gt 1 ] && {
        TSR=`python lib/curlies.py "RIB routing table for $N" \< \> < $OF | egrep "^s"`
        echo "$TSR"

        NH=`python lib/curlies.py "RIB nexthops for $N" \< \> < $OF`
        echo "$N NHOPS: $NH"
    }
done

#unlink $OF
