#!/usr/bin/env bash
# Exercise 1: access-log analytics with awk, sort and uniq (easy)
# Run with: bash linux_bash_scripting_exercise_1.sh
#
# Input (stdin): nginx "combined"-style lines, e.g.
#   203.0.113.5 - - [20/Oct/2026:10:00:01 +0000] "GET /api/pets HTTP/1.1" 200 512 "-" "curl/8.5" 0.120
# Fields (split on spaces): $1 IP, $6 "METHOD, $7 PATH, $9 STATUS, $10 BYTES,
# last field = request time in seconds.
#
# STEP 1: top_ips N        — "COUNT IP" for the N most frequent IPs, biggest first
#                            (ties: IP ascending)
# STEP 2: status_classes   — "2xx COUNT", "3xx COUNT", "4xx COUNT", "5xx COUNT"
#                            (all four lines, even if 0), in that order
# STEP 3: error_rate       — percentage of 5xx responses with one decimal (e.g. "12.5")
# STEP 4: slow_paths SECS  — unique paths (without query string) that had at least
#                            one request slower than SECS, sorted alphabetically
# STEP 5: bytes_by_path    — "PATH TOTAL_BYTES" for the path with the most total bytes

set -uo pipefail

top_ips() {
  # TODO
  :
}

status_classes() {
  # TODO
  :
}

error_rate() {
  # TODO
  :
}

slow_paths() {
  # TODO
  :
}

bytes_by_path() {
  # TODO
  :
}

# --- self-check: do not modify below this line ---
LOG='203.0.113.5 - - [20/Oct/2026:10:00:01 +0000] "GET /api/pets HTTP/1.1" 200 512 "-" "curl/8.5" 0.120
203.0.113.5 - - [20/Oct/2026:10:00:02 +0000] "GET /api/pets?page=2 HTTP/1.1" 200 498 "-" "curl/8.5" 0.090
198.51.100.7 - - [20/Oct/2026:10:00:02 +0000] "POST /api/orders HTTP/1.1" 500 120 "-" "app/2.1" 2.400
203.0.113.9 - - [20/Oct/2026:10:00:03 +0000] "GET /images/rex.jpg HTTP/1.1" 200 250000 "-" "Mozilla/5.0" 0.300
198.51.100.7 - - [20/Oct/2026:10:00:04 +0000] "POST /api/orders HTTP/1.1" 201 300 "-" "app/2.1" 0.800
203.0.113.5 - - [20/Oct/2026:10:00:05 +0000] "GET /login HTTP/1.1" 302 0 "-" "Mozilla/5.0" 0.010
192.0.2.44 - - [20/Oct/2026:10:00:06 +0000] "GET /admin HTTP/1.1" 403 150 "-" "scanner" 0.005
198.51.100.7 - - [20/Oct/2026:10:00:07 +0000] "GET /api/pets HTTP/1.1" 503 90 "-" "app/2.1" 1.600'

all_ok=true
check() {
  if [[ "$2" == "$3" ]]; then echo "ok   $1"; else echo "FAIL $1"; echo "     got:      $(printf '%s' "$2" | tr '\n' '|')"; echo "     expected: $(printf '%s' "$3" | tr '\n' '|')"; all_ok=false; fi
}

check "top_ips 2" "$(printf '%s\n' "$LOG" | top_ips 2)" "$(printf '3 198.51.100.7\n3 203.0.113.5')"
check "status_classes" "$(printf '%s\n' "$LOG" | status_classes)" "$(printf '2xx 4\n3xx 1\n4xx 1\n5xx 2')"
check "error_rate" "$(printf '%s\n' "$LOG" | error_rate)" "25.0"
check "slow_paths 1.0" "$(printf '%s\n' "$LOG" | slow_paths 1.0)" "$(printf '/api/orders\n/api/pets')"
check "bytes_by_path" "$(printf '%s\n' "$LOG" | bytes_by_path)" "/images/rex.jpg 250000"

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