#!/usr/bin/sh
set -eu

usage() {
  echo "usage: yabo-add <url> [name]" >&2
  exit 64
}

CONFIG=${YA_CONFIG:-/etc/yabo/config}
# shellcheck source=/dev/null
. "$CONFIG"
LIB=${YA_LIB:-/usr/share/yabo/lib.sh}
# shellcheck source=/dev/null
. "$LIB"

[ "$#" -ge 1 ] || usage
url=$1
name=${2:-}
rec="$YA_ROOT/subscriptions.rec"

# Schema-in-code: create the file with the current %allowed if absent, instead
# of a shipped seed the playbook could never migrate.
ensure_subscriptions "$rec"

# Resolve the stable channel id now so the RSS detector can hit the feed
# endpoint (feeds/videos.xml?channel_id=UC...) without re-scraping each run.
# channel_id is a playlist-level field, so it must be read with the "playlist:"
# print prefix; a plain --print channel_id on a --flat-playlist entry yields NA.
# --playlist-items 0 fetches the channel metadata without extracting any video.
cid=$(yt-dlp --js-runtimes node --flat-playlist --playlist-items 0 \
  --print "playlist:%(channel_id)s" "$url" 2>/dev/null | head -n1) || true
case $cid in
  UC*) ;;
  *) echo "cannot resolve channel_id for $url (got '${cid:-}')" >&2; exit 1 ;;
esac

set -- -t Subscription -f Url -v "$url" \
       -f Added -v "$(date +%F)" -f Enabled -v yes \
       -f ChannelId -v "$cid"
[ -n "$name" ] && set -- "$@" -f Name -v "$name"

# %key: Url makes recins fail on a duplicate — surface that as exit 1.
recins "$@" "$rec" || { echo "already subscribed or invalid: $url" >&2; exit 1; }
echo "added: $url"

# Populate the ledger now instead of waiting for the next tick; runs the full
# detector (other channels just 304, so it's cheap), best-effort — timer retries.
RSS=${YA_RSS:-/usr/libexec/yabo/yabo-rss}
if [ -x "$RSS" ]; then
  "$RSS" || echo "note: initial detection fetch failed; the timer will retry" >&2
fi
