#!/bin/zsh
set -euo pipefail

CONFIG="/Users/soren/.config/podsync/config.toml"
SERVICE="com.soren.podsync"
BASE_URL="https://mini.taila1ac2d.ts.net"

usage() {
  print -u2 "Usage: add-podcast-playlist.sh FEED_ID YOUTUBE_PLAYLIST_URL"
  print -u2 "Example: add-podcast-playlist.sh history_playlist 'https://www.youtube.com/playlist?list=PL...'"
  exit 2
}

[[ $# -eq 2 ]] || usage

feed_id="$1"
playlist_url="$2"

if [[ ! "$feed_id" =~ '^[a-z][a-z0-9_]*$' ]]; then
  print -u2 "FEED_ID must start with a lowercase letter and contain only lowercase letters, digits, and underscores."
  exit 2
fi

if [[ ! "$playlist_url" =~ '^https?://(www\.)?(youtube\.com|youtu\.be)/' ]] || [[ "$playlist_url" != *"list="* ]]; then
  print -u2 "The URL must be a YouTube playlist URL containing a list= parameter."
  exit 2
fi

if [[ ! -r "$CONFIG" ]]; then
  print -u2 "Cannot read $CONFIG"
  exit 1
fi

if grep -Fq "[feeds.${feed_id}]" "$CONFIG"; then
  print -u2 "Feed '${feed_id}' already exists in $CONFIG"
  exit 1
fi

playlist_id="${playlist_url##*list=}"
playlist_id="${playlist_id%%&*}"
if [[ ! "$playlist_id" =~ '^[A-Za-z0-9_-]+$' ]]; then
  print -u2 "The playlist ID contains unexpected characters."
  exit 2
fi
playlist_url="https://www.youtube.com/playlist?list=${playlist_id}"
if grep -Fq "list=${playlist_id}" "$CONFIG"; then
  print -u2 "That YouTube playlist is already configured."
  exit 1
fi

backup="${CONFIG}.backup.$(date -u +%Y%m%dT%H%M%SZ)"
cp -p "$CONFIG" "$backup"

{
  print ""
  print "[feeds.${feed_id}]"
  print "url = \"${playlist_url}\""
  print 'update_period = "1h"'
  print 'format = "audio"'
  print 'quality = "high"'
  print 'playlist_sort = "asc"'
  print 'opml = true'
  print 'private_feed = true'
} >> "$CONFIG"

launchctl kickstart -k "gui/$(id -u)/${SERVICE}"

feed_url="${BASE_URL}/${feed_id}.xml"
print "Added feed '${feed_id}'."
print "Backup: ${backup}"
print "Podcast URL: ${feed_url}"
print "Podsync is restarting; initial audio downloads and feed generation may take several minutes."
