#!/bin/bash

# Required software: yt-dlp

# Extract RSS-url from YouTube channel url.

VERBOSE=true
RESPONSE_PREFIX="https://www.youtube.com/channel/"
URL="$1"

echoErr() {
    >&2 echo "$1"
}

if ! command -v yt-dlp 2>&1 >/dev/null
then
    echoErr "$0 ERROR: yt-dlp is not installed."
    exit 1
fi

if [ -z "$URL" ]
then
    echoErr "$0 ERROR: No URL as argument provided. Please try again."
    exit 1
fi

[ "$VERBOSE" = true ] && echo "$0 INFO: Trying to extract RSS-url from channel '$URL'."
RESPONSE="$(yt-dlp --playlist-items 0 -O playlist:channel_url --print channel_url $URL 2> /dev/null)"

if [ -z "$RESPONSE" ]
then
    echoErr "$0 ERROR: Channel does not exist."
    exit 1
fi

# Deletes longest match of $RESPONSE_PREFIX from front of $RESPONSE using bash parameter expansion
CHANNEL_ID="${RESPONSE##$RESPONSE_PREFIX}"

echo "https://www.youtube.com/feeds/videos.xml?channel_id="$CHANNEL_ID""
