#!/bin/bash
# Skool Video Downloader — YouTube helper (macOS)
# https://tailsgate.com/skool-video-downloader/youtube
#
# Usage:  curl -fsSL https://tailsgate.com/skool-yt.sh | bash -s -- "https://www.youtube.com/watch?v=VIDEO_ID"
#
# What it does, in plain words:
#   1. Puts a private copy of yt-dlp (the open-source video tool) in ~/.skool-dl
#   2. Makes sure ffmpeg is available (uses yours if you have one, otherwise
#      drops a private static copy next to yt-dlp)
#   3. Downloads the video you passed in to your Downloads folder
# It never uses sudo, never touches your system Python, PATH, or Homebrew,
# and re-running it is always safe — it self-heals and self-updates.
#
# Design notes (why it dodges the usual traps):
#   • The standalone yt-dlp binary embeds its own Python — machines with no
#     Python, Apple's old 3.9, conda, or pyenv all behave identically.
#   • We never use a yt-dlp already on your PATH (could be years old and
#     broken against today's YouTube); our copy self-updates on every run.
#   • ffmpeg is required to merge YouTube's separate video+audio tracks. Any
#     working ffmpeg is fine and effectively never rots, so we prefer an
#     existing one and fall back to a pinned static build (same builds our
#     Whop helper has shipped to customers on both Intel and Apple Silicon).
#   • Terminal downloads carry no App-Store-style quarantine, but we strip
#     the attribute defensively anyway in case this script's files were
#     fetched by a browser first.

set -u

SUPPORT="support@tailsgate.com"
DIR="$HOME/.skool-dl"
BIN="$DIR/yt-dlp"
YTDLP_URL="https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos"
# Pinned static ffmpeg (arch-native). ffmpeg doesn't rot the way yt-dlp does,
# so pinning is safe and keeps the download deterministic.
FFMPEG_URL_ARM64="https://ffmpeg.martin-riedl.de/download/macos/arm64/1783011502_8.1.2/ffmpeg.zip"
FFMPEG_URL_AMD64="https://ffmpeg.martin-riedl.de/download/macos/amd64/1783018342_8.1.2/ffmpeg.zip"

say()  { printf '%s\n' "$*"; }
fail() {
  say ""
  say "✗ $1"
  say "  Nothing on your Mac was changed outside of $DIR."
  say "  Email $SUPPORT with a screenshot of this window and we'll sort it out personally."
  exit 1
}

[ "$(uname -s)" = "Darwin" ] && : || fail "This helper is for macOS. On Windows, follow the Windows tab on the guide page."

mkdir -p "$DIR" || fail "Couldn't create $DIR (disk permissions?)."

# ── 1. yt-dlp ────────────────────────────────────────────────────────────────
if [ -x "$BIN" ] && "$BIN" --version >/dev/null 2>&1; then
  # Already installed → quick self-update so YouTube changes can't rot it.
  say "→ Checking for yt-dlp updates…"
  "$BIN" -U >/dev/null 2>&1 || true
else
  say "→ Downloading yt-dlp (~35 MB, one time)…"
  rm -f "$BIN"
  curl -fSL --retry 3 --connect-timeout 20 -o "$BIN" "$YTDLP_URL" \
    || fail "Couldn't download yt-dlp. Check your internet connection and re-run the same command."
  chmod +x "$BIN"
  xattr -d com.apple.quarantine "$BIN" 2>/dev/null || true
  "$BIN" --version >/dev/null 2>&1 \
    || fail "yt-dlp downloaded but won't run on this Mac (macOS too old?)."
fi
say "  ✓ yt-dlp $("$BIN" --version 2>/dev/null || echo ready)"

# ── 2. ffmpeg ────────────────────────────────────────────────────────────────
# Any ffmpeg that actually executes is good enough. Prefer existing installs
# (Homebrew or otherwise); otherwise drop a private static copy in $DIR.
FFMPEG=""
for cand in "$DIR/ffmpeg" /opt/homebrew/bin/ffmpeg /usr/local/bin/ffmpeg "$(command -v ffmpeg 2>/dev/null || true)"; do
  if [ -n "$cand" ] && [ -x "$cand" ] && "$cand" -version >/dev/null 2>&1; then FFMPEG="$cand"; break; fi
done
if [ -z "$FFMPEG" ]; then
  case "$(uname -m)" in
    arm64) FF_URL="$FFMPEG_URL_ARM64" ;;
    *)     FF_URL="$FFMPEG_URL_AMD64" ;;
  esac
  say "→ Downloading ffmpeg (~25 MB, one time — merges video and audio tracks)…"
  curl -fSL --retry 3 --connect-timeout 20 -o "$DIR/ffmpeg.zip" "$FF_URL" \
    || fail "Couldn't download ffmpeg. Check your internet connection and re-run the same command."
  ( cd "$DIR" && unzip -oq ffmpeg.zip && rm -f ffmpeg.zip ) \
    || fail "Couldn't unpack ffmpeg."
  chmod +x "$DIR/ffmpeg"
  xattr -d com.apple.quarantine "$DIR/ffmpeg" 2>/dev/null || true
  "$DIR/ffmpeg" -version >/dev/null 2>&1 || fail "ffmpeg downloaded but won't run on this Mac."
  FFMPEG="$DIR/ffmpeg"
fi
say "  ✓ ffmpeg ready"

# ── 3. Download ──────────────────────────────────────────────────────────────
if [ "$#" -eq 0 ]; then
  say ""
  say "✓ Setup complete. To download a video, run:"
  say "  curl -fsSL https://tailsgate.com/skool-yt.sh | bash -s -- \"https://www.youtube.com/watch?v=VIDEO_ID\""
  exit 0
fi

STATUS=0
for URL in "$@"; do
  say ""
  say "→ Downloading: $URL"
  # h264-in-mp4 first so the file opens in QuickTime on every Mac (AV1/VP9
  # don't); fall back through mp4 → best available.
  # </dev/null: stdin is this script when piped through bash — never let
  # yt-dlp read from it.
  if "$BIN" \
      --ffmpeg-location "$FFMPEG" \
      --no-playlist \
      -f "bv*[vcodec^=avc1]+ba[ext=m4a]/bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]/bv*+ba/b" \
      --merge-output-format mp4 \
      -o "$HOME/Downloads/%(title)s.%(ext)s" \
      --no-mtime \
      "$URL" </dev/null; then
    say "✓ Saved to your Downloads folder."
  else
    STATUS=1
    say "✗ That video didn't download. Common causes: private/members-only video, or"
    say "  YouTube changed something (re-run this same command — it self-updates)."
    say "  Still stuck? Email $SUPPORT and include the video link."
  fi
done
exit $STATUS
