#!/usr/bin/env bash
# Fetch each sampled row's first source URL (RULES_spotcheck.txt). Plain client name; no retries of a
# refused URL; the row's next listed URL is tried once if the first is refused or dead.
# Usage: bash 03_spotcheck_fetch.sh <base>, after 03_spotcheck_draw.py --base <base> has written
# <base>/results/spotcheck_sample.txt. The pages go to <base>/spotcheck/<sheet_row>/ to be read by hand; they are
# third-party pages, and none is hosted with our page. "botcheck_or_denied" is a first screen only: on our run every
# such page turned out to be the article itself, with a form or script that mentions a captcha.
set -u
V="${1:?usage: bash 03_spotcheck_fetch.sh <base>}"
OUT=$V/spotcheck
mkdir -p "$OUT"
LOG=$OUT/fetch_log.tsv
printf "fetched_utc\tsample\tsheet_row\tattempt\turl\thttp\tbytes\tcontent_type\tfinal_url\tverdict\n" > "$LOG"
tail -n +3 "$V/results/spotcheck_sample.txt" | while IFS=$'\t' read -r lab sr date cert urls; do
  mkdir -p "$OUT/$sr"
  n=0
  for u in $urls; do
    n=$((n+1))
    f="$OUT/$sr/source$n.html"
    t=$(date -u +%Y-%m-%dT%H:%M:%SZ)
    r=$(curl -sS -L --max-time 40 -A "factchecked-research/1.0" -o "$f" -w "%{http_code}\t%{size_download}\t%{content_type}\t%{url_effective}" "$u" 2>/dev/null) || r="000\t0\t-\t-"
    code=$(printf "%b" "$r" | cut -f1)
    verdict=ok
    if [ "$code" = "403" ] || [ "$code" = "429" ] || [ "$code" = "401" ]; then verdict=refused; fi
    if [ "$code" = "404" ] || [ "$code" = "410" ] || [ "$code" = "000" ] || [ "$code" = "500" ] || [ "$code" = "502" ] || [ "$code" = "503" ]; then verdict=dead; fi
    if [ "$verdict" = "ok" ] && [ -s "$f" ]; then
      if grep -qiE "cf-chl|challenge-platform|Just a moment\.\.\.|Attention Required|captcha|are you a robot|px-captcha|perimeterx|distil_r_captcha|Access Denied" "$f"; then verdict=botcheck_or_denied; fi
    fi
    printf "%s\t%s\t%s\t%d\t%s\t%b\t%s\n" "$t" "$lab" "$sr" "$n" "$u" "$r" "$verdict" >> "$LOG"
    if [ "$verdict" = "ok" ]; then break; fi
    if [ $n -ge 2 ]; then break; fi
  done
done
echo done
