#!/bin/bash
# panel-guard — crawler brake: when the server is busy, bulk crawlers (AI and SEO bots) are told to come back later
# (HTTP 503 + Retry-After), so people and search engines keep getting fast pages. Google and Bing are never slowed.
#   panel-guard tick      run every minute (by panel-metrics): sets the level from the load per CPU core
#                         level 0 = normal · 1 = busy: crawlers get 1 of 3 requests · 2 = overloaded: crawlers wait
#   panel-guard status    JSON: enabled, level, since, load, cores
#   panel-guard on | off  switch the brake on or off (off = never slow anyone)
#   panel-guard install   write the web server rule (/etc/httpd/conf.d/02-panel-guard.conf)
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
CONF=/etc/panel/guard.conf; RUN=/run/panel; STATE=/var/lib/panel/guard.json
ENABLED=1; [ -f "$CONF" ] && . "$CONF"
level() { if [ -f "$RUN/guard-2" ]; then echo 2; elif [ -f "$RUN/guard-1" ]; then echo 1; else echo 0; fi; }
setlevel() {
  install -d -m 755 "$RUN"
  case "$1" in 0) rm -f "$RUN/guard-1" "$RUN/guard-2" ;; 1) : > "$RUN/guard-1"; rm -f "$RUN/guard-2" ;; 2) : > "$RUN/guard-1"; : > "$RUN/guard-2" ;; esac
}
case "${1:-status}" in
  tick)
    cores=$(nproc); read -r l1 l5 _ < /proc/loadavg; cur=$(level); new=$cur
    # CPU the hosting provider is holding back ("steal", e.g. a throttled VPS) is not available: count only what is left
    read -r _ a1 b1 c1 d1 e1 f1 g1 h1 _ < /proc/stat; sleep 2; read -r _ a2 b2 c2 d2 e2 f2 g2 h2 _ < /proc/stat
    tot=$(( (a2+b2+c2+d2+e2+f2+g2+h2) - (a1+b1+c1+d1+e1+f1+g1+h1) )); [ "$tot" -gt 0 ] || tot=1
    steal=$(( 100 * (h2 - h1) / tot ))
    cores=$(awk -v c="$cores" -v s="$steal" 'BEGIN{e = c * (100 - s) / 100; if (e < 0.75) e = 0.75; printf "%.2f", e}')
    if [ "$ENABLED" != 1 ]; then new=0
    else
      # up quickly (1-minute load), down only when the 5-minute load has calmed too
      new=$(awk -v l1="$l1" -v l5="$l5" -v c="$cores" -v cur="$cur" 'BEGIN{
        a=l1/c; b=l5/c; n=cur
        if (a>=2.5) n=2; else if (a>=1.25 && n<1) n=1
        if (n==2 && a<1.75 && b<2.0) n=1
        if (n==1 && a<1.0 && b<1.25) n=0
        print n}')
    fi
    if [ "$new" != "$cur" ] || [ ! -f "$STATE" ]; then
      setlevel "$new"; LOGNAME_PANEL=panel log "crawler brake: level $cur -> $new (load $l1, $cores usable cores, $steal% held back by the host)"
      echo "$(date -u '+%F %T')  server load $l1 with $cores usable CPU cores ($steal% held back by the hosting provider): crawler brake $([ "$new" = 0 ] && echo "off again" || echo "level $new ($([ "$new" = 2 ] && echo "crawlers wait" || echo "crawlers get 1 request in 3"))")" >> "$PANEL_LOG/busy.log"
      printf '{"level":%s,"since":%s,"load":%s,"cores":%s}\n' "$new" "$(date +%s)" "$l1" "$cores" > "$STATE.new" && mv -f "$STATE.new" "$STATE"; chmod 644 "$STATE"
    fi ;;
  status)
    since=$(sed -n 's/.*"since":\([0-9]*\).*/\1/p' "$STATE" 2>/dev/null || true)
    printf '{"enabled":%s,"level":%s,"since":%s,"load":%s,"cores":%s,"installed":%s}\n' "$([ "$ENABLED" = 1 ] && echo true || echo false)" "$(level)" "${since:-0}" "$(cut -d' ' -f1 /proc/loadavg)" "$(nproc)" "$([ -f /etc/httpd/conf.d/02-panel-guard.conf ] && echo true || echo false)" ;;
  on)  echo "ENABLED=1" > "$CONF"; rm -f "$STATE"; echo "Crawler brake is on." ;;
  off) echo "ENABLED=0" > "$CONF"; setlevel 0; rm -f "$STATE"; echo "Crawler brake is off." ;;
  install)
    cat > /etc/httpd/conf.d/02-panel-guard.conf <<'C'
# Incaine Panel crawler brake (panel-guard). Bulk crawlers are slowed only while /run/panel/guard-1 or guard-2 exist.
# Search engines people actually arrive from (Googlebot, bingbot, DuckDuckBot) are deliberately not in this list.
SetEnvIfNoCase User-Agent "(GPTBot|OAI-SearchBot|ChatGPT-User|ClaudeBot|Claude-SearchBot|Claude-User|anthropic-ai|Applebot|Amazonbot|Bytespider|meta-externalagent|meta-externalfetcher|FacebookBot|CCBot|PerplexityBot|Perplexity-User|ElevenlabsCrawler|PetalBot|SemrushBot|AhrefsBot|DotBot|MJ12bot|DataForSeoBot|ImagesiftBot|Diffbot|YandexBot|SeznamBot|Barkrowler|BLEXBot|serpstatbot|Timpibot|omgili|YouBot|cohere-ai|AI2Bot|iaskspider|Scrapy|python-requests|Go-http-client|GoogleOther|Google-Extended|TikTokSpider|Sogou|Baiduspider|AwarioBot|MauiBot|coccocbot|Qwantbot|Mojeek|trendictionbot|Brightbot|SiteAuditBot|ZoominfoBot|DuckAssistBot|MistralAI-User|Kangaroo Bot|PanguBot|Webzio|ISSCyberRiskCrawler|WellKnownBot)" panel_bulk_bot
<Directory "/home">
    # level 2 (overloaded): every crawler request waits · level 1 (busy): crawlers are served 20 seconds of each minute
    <If "reqenv('panel_bulk_bot') == '1' && %{REQUEST_URI} != '/robots.txt' && ( -f '/run/panel/guard-2' || ( -f '/run/panel/guard-1' && %{TIME_SEC} -ge 20 ) )">
        Redirect 503
    </If>
</Directory>
Header always set Retry-After "900" "expr=%{REQUEST_STATUS} == 503 && reqenv('panel_bulk_bot') == '1'"
C
    apachectl -t 2>&1 | tail -1 | grep -q "Syntax OK" || { apachectl -t 2>&1 | tail -3 >&2; rm -f /etc/httpd/conf.d/02-panel-guard.conf; die "web server did not accept the rule — removed again"; }
    systemctl reload httpd; echo "Crawler brake installed." ;;
  *) sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;;
esac
