#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# Domain Monitor — ISP agent
#
# Run this on a device connected to ONE Malaysian ISP (one per SIM/line:
# Celcom, Digi, Maxis, U Mobile, or your Unifi line). It checks all your domains
# over that real ISP connection and reports which are blocked back to the dashboard.
#
# Works on:  Android (Termux: `pkg install bash curl`), any Linux, macOS, Git Bash.
#
# SETUP — edit the 3 values below, then run:   bash isp-agent.sh
# To loop every 30 min:                        bash isp-agent.sh --loop 1800
# ─────────────────────────────────────────────────────────────────────────────

# 1) Your dashboard's agent endpoint (reachable from this device).
#    On the same PC use localhost; from a phone use the PC's LAN IP, e.g.
#    http://192.168.0.10/domain-monitor/api/agent.php
API="http://localhost/domain-monitor/api/agent.php"

# 2) The agent token from dashboard → Settings → Agent token.
TOKEN="PASTE_YOUR_AGENT_TOKEN_HERE"

# 3) The ISP this device is connected to (free text — shown in the dashboard).
ISP="Celcom"

# ── MCMC block-page signatures (case-insensitive) ────────────────────────────
SIGNATURES='makluman|telah disekat|notis sekatan|laman web ini telah disekat|akses ke laman web ini|not available in malaysia|makluman.seskm.gov.my|makluman2.skmm.gov.my'

run_once() {
  echo "[$(date '+%F %T')] ISP=$ISP — fetching domain list…"
  local list
  list=$(curl -s "$API?action=domains&token=$TOKEN")
  if [ -z "$list" ] || echo "$list" | grep -qi forbidden; then
    echo "  ! could not get domains (check API URL / token)"; return 1
  fi

  local data="" total=0 blocked=0
  while IFS=$'\t' read -r id url; do
    [ -z "$id" ] && continue
    total=$((total+1))
    # follow redirects, capture body + final URL; -k tolerates cert issues on block pages
    local out final body b note
    out=$(curl -sLk -m 25 -A "Mozilla/5.0 (ISP-agent)" -w $'\n__FINAL__%{url_effective}' "$url" 2>/dev/null)
    final=$(printf '%s' "$out" | sed -n 's/^__FINAL__//p' | tail -1)
    body=$(printf '%s' "$out" | sed '/^__FINAL__/d')
    if [ -z "$body" ] && [ -z "$final" ]; then
      b=""; note="no response"                 # unknown / down
    elif printf '%s %s' "$final" "$body" | grep -qiE "$SIGNATURES"; then
      b=1; note="MCMC notice page"; blocked=$((blocked+1))
    else
      b=0; note="ok"
    fi
    data+="${id}|${b}|${final}|${note}"$'\n'
  done <<< "$list"

  local resp
  resp=$(curl -s -X POST "$API" \
      --data-urlencode "token=$TOKEN" \
      --data-urlencode "isp=$ISP" \
      --data-urlencode "data=$data")
  echo "  checked $total, blocked $blocked → $resp"
}

if [ "$1" = "--loop" ]; then
  INTERVAL="${2:-1800}"
  echo "Looping every ${INTERVAL}s. Ctrl+C to stop."
  while true; do run_once; sleep "$INTERVAL"; done
else
  run_once
fi
