#!/usr/bin/env bash set -euo pipefail # Track temp files for cleanup tmpfiles=() cleanup() { for f in "${tmpfiles[@]}"; do [ -f "$f" ] && rm -f "$f" done } trap 'cleanup; exit 130' INT trap 'cleanup' EXIT mkdir -p channels file="$1" start_id="${2:-}" skip=true while read -r id; do # Skip logic if [ -n "$start_id" ] && $skip; then if [ "$id" = "$start_id" ]; then skip=false else continue fi fi playlist_id="UU${id:2}" outfile="channels/${id}.json" tmpfile="${outfile}.tmp.$$" if [ ! -f "$outfile" ]; then echo "Fetching $id..." tmpfiles+=("$tmpfile") if yt-dlp \ -j \ --flat-playlist \ --lazy-playlist \ --extractor-arg "youtubetab:approximate_date" \ "https://www.youtube.com/playlist?list=$playlist_id" \ > "$tmpfile"; then mv -f "$tmpfile" "$outfile" # remove from tracked list since it's now promoted tmpfiles=("${tmpfiles[@]/$tmpfile}") else echo "Failed to fetch $id" >&2 rm -f "$tmpfile" tmpfiles=("${tmpfiles[@]/$tmpfile}") fi else echo "Skipping $id (already exists)" >&2 fi done < "$file"