#! /bin/bash
#
# Move images referenced by markdown files into a Cloudflare R2 bucket,
# then rewrite the links to point at $IMG_HOST.
#
#   https://topo.tw/photos/<path>              -> photos/<path>
#   https://pbs.twimg.com/media/<id>.<ext>     -> photos/twitter/<id>.<ext>
#
# Sources tried in order: --src DIR, the live URL, the Wayback Machine.
# Links inside fenced code blocks are ignored.
#
# Usage: migrate-images.sh [--apply] [--src DIR] [FILE...]
#   Without --apply, only report what would be done.

set -e

declare -r IMG_BUCKET=${IMG_BUCKET:-photos}
declare -r IMG_HOST=${IMG_HOST:-https://img.topo.tw}
declare -r URL_PATTERN='https?://(topo\.tw/photos|pbs\.twimg\.com/media)/[^]) "'"'"'<>]+'

apply=false
src_dir=
while [ $# -gt 0 ]; do
  case "$1" in
    --apply) apply=true ;;
    --src) src_dir=${2:?--src needs a directory}; shift ;;
    -h|--help) sed -n '3,/^$/ s/^# \{0,1\}//p' "$0"; exit 0 ;;
    *) break ;;
  esac
  shift
done

cd "$(dirname "$0")/.."
[ $# -gt 0 ] && files=("$@") || mapfile -d '' files < <(git ls-files -z '*.md')

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

# Print URLs outside fenced code blocks
extract_urls() {
  awk '/^[[:space:]]*```/ { fence = !fence; next } !fence' "$1" | grep -oE "$URL_PATTERN" || true
}

# Map URL to object key and candidate download URLs
plan() {
  local url=$1 path id ext
  case "$url" in
    *topo.tw/photos/*)
      path=${url#*topo.tw/photos/}
      key=photos/$path
      sources=()
      [ -n "$src_dir" ] && sources+=("file://$(realpath "$src_dir")/$path")
      sources+=("https://topo.tw/photos/$path" "https://web.archive.org/web/2id_/$url")
      ;;
    *pbs.twimg.com/media/*)
      id=${url#*/media/}
      if [[ $id == *format=* ]]; then
        ext=${id#*format=}; ext=${ext%%&*}; id=${id%%\?*}
      else
        ext=${id##*.}; id=${id%.*}
      fi
      key=photos/twitter/$id.$ext
      sources=("https://pbs.twimg.com/media/$id?format=$ext&name=orig" "$url"
               "https://web.archive.org/web/2id_/$url")
      ;;
  esac
}

# Download the first source that returns an image
fetch() {
  local out=$1 s; shift
  for s in "$@"; do
    curl -fsSL --max-time 30 -o "$out" "$s" 2>/dev/null || continue
    [[ $(file -b --mime-type "$out") == image/* ]] && { echo "$s"; return 0; }
  done
  return 1
}

declare -A done_keys
ok=0 missing=0
for f in "${files[@]}"; do
  while read -r url; do
    plan "$url"
    new=$IMG_HOST/$key

    if [ -z "${done_keys[$key]}" ]; then
      out=$tmp/${key//\//_}
      if ! from=$(fetch "$out" "${sources[@]}"); then
        echo "MISSING $url ($f)" >&2
        missing=$((missing + 1))
        continue
      fi
      if $apply; then
        cf r2 objects put "$key" -q --bucket-name "$IMG_BUCKET" \
          --file "$out" --content-type "$(file -b --mime-type "$out")" >/dev/null
      fi
      done_keys[$key]=1
      echo "OK      $key <- $from"
    fi

    if $apply; then
      OLD=$url NEW=$new perl -pi -e 's/\Q$ENV{OLD}\E/$ENV{NEW}/g' "$f"
    fi
    ok=$((ok + 1))
  done < <(extract_urls "$f" | sort -u)
done

$apply || echo "(dry run, pass --apply to upload and rewrite)"
echo "links: $ok ok, $missing missing"
