#!/bin/bash
# Sorts the downloads from the TPT backup kit into one folder per product, in Documents/TPT Store Backup.
# It goes by arrival order: each "<id> - <title> - listing.zip" is followed by that product's own files.

DOWNLOADS="${TPT_DOWNLOADS:-$HOME/Downloads}"
TARGET="${TPT_TARGET:-$HOME/Documents/TPT Store Backup}"
WINDOW=600   # seconds: a product's files arrive within this time after its listing zip
PREVIEW_RE='^[0-9a-f]{32}( \([0-9]+\))?\.pdf$'   # TPT previews arrive with a random hex name

mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1"; }   # GNU first: on a Mac it fails and the BSD form runs
finish() { echo; read -r -p "Press Enter to close this window." _; exit 0; }

echo "Looking in: $DOWNLOADS"
cd "$DOWNLOADS" || { echo "Cannot open $DOWNLOADS"; finish; }
if ! ls -1 | grep -q ' - listing\.zip$'; then echo "No TPT backup files found in your Downloads folder. Nothing to do."; finish; fi
if ls -1 | grep -qE '\.(crdownload|download)$'; then echo "Some downloads are still in progress. Wait until the browser has finished, then run this again."; finish; fi

mkdir -p "$TARGET/_listing-zips"
current=""; start=0; count=0
while IFS= read -r f; do
  [ -f "$f" ] || continue
  t=$(mtime "$f")
  if [[ "$f" == *" - listing.zip" ]]; then
    current="${f% - listing.zip}"; start=$t
    mkdir -p "$TARGET/$current"
    unzip -oq "$f" -d "$TARGET/$current" && mv -f "$f" "$TARGET/_listing-zips/"
    count=$((count + 1)); echo "Sorted: $current"
    continue
  fi
  [ -n "$current" ] || continue                     # arrived before any listing zip
  [ $((t - start)) -le $WINDOW ] || continue        # too long after it: not part of the backup
  if [[ "$f" =~ $PREVIEW_RE ]]; then sub="preview"; name="preview.pdf"
  else
    sub="product-file"; ext=""; base="$f"
    [[ "$f" == *.* ]] && { ext=".${f##*.}"; base="${f%.*}"; }
    name="$(printf '%s' "$base" | sed -E 's/(-[0-9]+)?( \([0-9]+\))?$//')$ext"
  fi
  mkdir -p "$TARGET/$current/$sub"
  dest="$TARGET/$current/$sub/$name"; n=2
  while [ -e "$dest" ]; do dest="$TARGET/$current/$sub/${name%.*}-$n.${name##*.}"; n=$((n + 1)); done
  mv "$f" "$dest"
done < <(ls -1tr)

# check every product got the files its details.txt lists
missing=""
for d in "$TARGET"/*/; do
  d="${d%/}"; [ -f "$d/details.txt" ] || continue
  for kind in product-file preview; do
    want=$(grep -c "^$kind: " "$d/details.txt")
    have=$(ls -1 "$d/$kind" 2>/dev/null | wc -l | tr -d ' ')
    [ "$have" -lt "$want" ] && missing="$missing\n  $(basename "$d"): $kind missing"
  done
done

echo
echo "Done: sorted $count listing(s) into $TARGET"
if [ -n "$missing" ]; then printf 'Some files did not arrive. Run the backup again for these listings:%b\n' "$missing"; fi
[ -z "$TPT_TARGET" ] && command -v open >/dev/null && open "$TARGET"
finish
