#!/usr/bin/env bash
# Exercise 1: parse traceroute output and find the bottleneck hop (easy-medium)
#
# This exercise does NOT require live network access — it analyzes a canned
# sample of traceroute output (embedded below as a heredoc), so it runs the
# same way in any sandbox/CI environment.
#
# STEP 1: implement `parse_hop_time` — given one line of traceroute output,
#         print just the numeric RTT in milliseconds (e.g. from
#         " 3  203.0.113.1        12.1 ms" print "12.1"). Print nothing for
#         a line that has no RTT (e.g. a "* * *" timeout line).
#
# STEP 2: implement `find_bottleneck_hop` — given the full traceroute output
#         (on stdin), find which hop-to-hop TRANSITION adds the most extra
#         latency (i.e. the biggest increase from one hop's RTT to the
#         next hop's RTT, not just the hop with the highest absolute RTT).
#         Print the hop number where the big jump ARRIVES (e.g. if hop 2 is
#         3.4ms and hop 3 is 12.1ms, the jump arrives at hop 3 — print "3").

set -euo pipefail

parse_hop_time() {
  local line="$1"
  # TODO: extract the RTT number (e.g. "14.2") from a line like:
  #   " 3  203.0.113.1        12.1 ms"
  # Print nothing if the line has no "ms" value (e.g. "* * *").
  # Hint: grep -oE '[0-9]+\.[0-9]+ ms' | grep -oE '[0-9]+\.[0-9]+'
  echo ""
}

find_bottleneck_hop() {
  # TODO: read traceroute lines from stdin, compute each hop's RTT via
  # parse_hop_time, track the previous hop's RTT, and print the hop number
  # where (this_hop_rtt - previous_hop_rtt) is largest. Skip lines with no
  # parseable RTT when computing deltas (don't treat a timeout as 0ms).
  echo ""
}

# --- self-check: do not modify below this line ---
SAMPLE_TRACE='
 1  192.168.1.1        1.2 ms
 2  10.20.0.1           3.4 ms
 3  203.0.113.1        12.1 ms
 4  198.51.100.9       14.0 ms
 5  93.184.216.34      14.3 ms
'

pass=true

got1=$(parse_hop_time " 3  203.0.113.1        12.1 ms")
if [[ "$got1" == "12.1" ]]; then
  echo "PASS: parse_hop_time extracts RTT from a normal hop line"
else
  echo "FAIL: parse_hop_time extracts RTT from a normal hop line (got '$got1', expected '12.1')"
  pass=false
fi

got2=$(parse_hop_time " 6  * * *")
if [[ -z "$got2" ]]; then
  echo "PASS: parse_hop_time returns nothing for a timeout line"
else
  echo "FAIL: parse_hop_time returns nothing for a timeout line (got '$got2', expected empty)"
  pass=false
fi

got3=$(echo "$SAMPLE_TRACE" | find_bottleneck_hop)
if [[ "$got3" == "3" ]]; then
  echo "PASS: find_bottleneck_hop identifies hop 3 as the biggest jump (2->3 is +8.7ms, the largest delta)"
else
  echo "FAIL: find_bottleneck_hop identifies hop 3 as the biggest jump (got '$got3', expected '3')"
  pass=false
fi

if $pass; then
  echo "PASS"
else
  echo "FAIL"
fi
