#!/usr/bin/env bash
# Download a public Pinterest board or section into a new directory.
set -euo pipefail

if [[ $# != 2 ]]; then
  echo "Usage: bash pinterest-board.sh BOARD_OR_SECTION_URL NEW_OUTPUT_DIRECTORY" >&2
  exit 2
fi
url=${1%%[?#]*}
url=${url%/}
# Accept Pinterest board and section paths, including regional Pinterest domains.
if [[ ! $url =~ ^https://([a-z]+\.)?pinterest\.([a-z]{2,3}|co\.[a-z]{2}|com\.[a-z]{2})/([^/]+)/([^/]+)(/[^/]+)?$ ]]; then
  echo "Supply the full HTTPS Pinterest board or section URL." >&2
  exit 2
fi
case "${BASH_REMATCH[3]}/${BASH_REMATCH[4]}" in
  pin/*|search/*|ideas/*|today/*|*/_created|*/_saved|*/pins)
    echo "Supply a board or section URL with an account and board name." >&2; exit 2 ;;
esac

for tool in gallery-dl jq file openssl; do
  command -v "$tool" >/dev/null || { echo "Install $tool and run again." >&2; exit 2; }
done
mkdir -- "$2" || { echo "Choose a new output directory with an existing parent." >&2; exit 1; }
cd -- "$2"
work=$(mktemp -d "$PWD/.pins.XXXXXX")
gallery-dl --config-ignore -o extractor.pinterest.sections=true \
  --filter "extension.lower() in ('jpg','jpeg','png','webp','gif','avif')" \
  --directory "$work" --filename '{id}-{num}.{extension}' --write-metadata \
  --Print-to-file 'file:{id}-{num}.{extension}' "$work/order.txt" -- "$url/"

[[ -s "$work/order.txt" ]] || { echo "Pinterest returned no downloadable images for this collection." >&2; exit 1; }
mkdir "$work/seen"
count=0
while IFS= read -r name; do
  [[ $name =~ ^[A-Za-z0-9_-]+-[0-9]+\.(jpg|jpeg|png|webp|gif|avif)$ ]] || { echo "Unexpected image filename." >&2; exit 1; }
  case "$(file -b --mime-type "$work/$name")" in
    image/jpeg) ext=jpg ;; image/png) ext=png ;; image/webp) ext=webp ;;
    image/gif) ext=gif ;; image/avif) ext=avif ;;
    *) echo "Could not verify image $name." >&2; exit 1 ;;
  esac
  checksum=$(openssl dgst -sha256 -r < "$work/$name")
  seen="$work/seen/${checksum%% *}"
  if [[ -f $seen ]]; then
    IFS= read -r slide < "$seen"
  else
    count=$((count + 1))
    printf -v slide '%04d.%s' "$count" "$ext"
    cp "$work/$name" "$slide"
    printf '%s\n' "$slide" > "$seen"
    printf '%s\n' "$slide" >> "$work/slides.txt"
  fi
  jq -ce --arg file "$slide" 'select(.id != null) | {
    file: $file, pin_url: ("https://www.pinterest.com/pin/" + (.id|tostring) + "/"),
    image_url: .url, source_url: (.link // null), credit: (.attribution.author_name // null)
  }' "$work/$name.json" >> "$work/pins.jsonl"
done < "$work/order.txt"

jq -s --arg board "$url/" --rawfile order "$work/slides.txt" \
  '{source: $board, slides: ($order | split("\n") | map(select(length > 0))), pins: .}' \
  "$work/pins.jsonl" > "$work/slides.json"
mv "$work/slides.json" slides.json
rm -r -- "$work"
printf 'Saved %d images and slides.json in %s\n' "$count" "$PWD"
