#!/bin/bash
# panel-traffic — who is visiting which site in the last N minutes (default 10), from the Apache access logs.
# Prints JSON: requests per site (all / pages), top visitors by kind (named bots, browsers), top IPs.
# Cached for 60 s in /var/lib/panel/traffic.json so dashboard refreshes stay cheap.
set -u
MIN="${1:-10}"; [[ "$MIN" =~ ^[0-9]+$ ]] && [ "$MIN" -le 120 ] || MIN=10
CACHE=/var/lib/panel/traffic.json
if [ "$MIN" = 10 ] && [ -s "$CACHE" ] && [ -n "$(find "$CACHE" -mmin -1 2>/dev/null)" ]; then cat "$CACHE"; exit 0; fi
since=$(date -d "-$MIN min" +%Y%m%d%H%M%S)   # same clock/timezone as the logs
shopt -s nullglob
out=$(for f in /var/log/httpd/sites/*.access.log; do
  d=$(basename "$f" .access.log)
  # only look at the tail of big logs; 400k lines is far more than 10 minutes on a busy site
  tail -n 400000 "$f" | awk -v site="$d" -v since="$since" '
    BEGIN { split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", m, " "); for (i = 1; i <= 12; i++) mon[m[i]] = sprintf("%02d", i) }
    {
      # [08/Nov/2026:18:55:01 +0000]  ->  20261108185501 (plain string compare, works in every awk)
      p = index($0, "["); if (!p) next
      t = substr($0, p + 1, 20)
      ts = substr(t, 8, 4) mon[substr(t, 4, 3)] substr(t, 1, 2) substr(t, 13, 2) substr(t, 16, 2) substr(t, 19, 2)
      if (ts < since) next
      n = split($0, q, "\""); url = q[2]; ua = (n >= 6 ? q[6] : "")
      sub(/^[A-Z]+ /, "", url); sub(/ HTTP\/.*$/, "", url)
      page = (url !~ /\.(css|js|mjs|png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|map|mp4|webm|mp3)(\?|$)/)
      kind = "other"
      if (match(ua, /(ClaudeBot|Claude-SearchBot|Claude-User|GPTBot|OAI-SearchBot|ChatGPT-User|PerplexityBot|Perplexity-User|Googlebot|Google-Extended|GoogleOther|bingbot|Applebot|Amazonbot|Bytespider|meta-externalagent|facebookexternalhit|CCBot|PetalBot|YandexBot|Baiduspider|AhrefsBot|SemrushBot|MJ12bot|DotBot|DataForSeoBot|BLEXBot|Barkrowler|ImagesiftBot|ElevenlabsCrawler|Timpibot|SeznamBot|Sogou|Twitterbot|LinkedInBot|Slackbot|Discordbot|TelegramBot|WhatsApp)/)) kind = substr(ua, RSTART, RLENGTH)
      else if (ua ~ /[Bb]ot|[Cc]rawl|[Ss]pider|[Ss]craper|curl|python-requests|Go-http|wget|HeadlessChrome/) kind = "other bots & scripts"
      else if (ua ~ /^Mozilla/) kind = "browsers (people)"
      print site "\t" page "\t" kind "\t" $1
    }'
done)
echo "$out" | awk -F'\t' -v min="$MIN" -v gen="$(date +%s)" '
  NF == 4 { all[$1]++; if ($2) { pg[$1]++; k[$3]++; ks[$3 "\t" $1]++; ip[$4]++; ips[$4 "\t" $1]++; tot++ } }
  function topsite(key, arr,   s, best, bn, x) { best = ""; bn = 0; for (x in arr) { split(x, s, "\t"); if (s[1] == key && arr[x] > bn) { bn = arr[x]; best = s[2] } } return best }
  END {
    printf "{\"generated\":%d,\"minutes\":%d,\"pages\":%d,\"sites\":[", gen, min, tot
    n = 0; for (s in all) { printf "%s{\"d\":\"%s\",\"all\":%d,\"pages\":%d}", (n++ ? "," : ""), s, all[s], pg[s] + 0 }
    printf "],\"agents\":["
    n = 0; for (x in k) { printf "%s[\"%s\",%d,\"%s\"]", (n++ ? "," : ""), x, k[x], topsite(x, ks) }
    printf "],\"ips\":["
    # only IPs with a noticeable share, to keep the output small
    n = 0; for (x in ip) if (ip[x] >= 50 || ip[x] * 20 >= tot) { printf "%s[\"%s\",%d,\"%s\"]", (n++ ? "," : ""), x, ip[x], topsite(x, ips) }
    print "]}"
  }' > "$CACHE.tmp" && chmod 644 "$CACHE.tmp" && { [ "$MIN" = 10 ] && mv "$CACHE.tmp" "$CACHE" && cat "$CACHE" || { cat "$CACHE.tmp"; rm -f "$CACHE.tmp"; }; }
