#!/bin/bash
# vim: noai:ts=4:sw=4:expandtab

declare -a full_pull_accounts=(
    "@Blondihacks"
    "@Clickspring"
    "@InheritanceMachining"
    "@Noralities"
    "@RedMeansRecording"
    "@sarahdavisbaker"
    "@SproutHaven"
)

function download_url() {
        # --cookies-from-browser firefox \
    yt-dlp \
        -o "%(uploader_id)s/%(playlist)s/%(playlist_autonumber)s - %(title)s [%(id)s].%(ext)s" \
        --playlist-reverse \
        --abort-on-error \
        --write-info-json \
        --download-archive archive.txt \
        --remote-components ejs:github \
        --cookies "~/Downloads/cookies.txt" \
        --js-runtimes node \
        -t sleep \
        -t mkv \
        "$1"
}

for yt_account in "${full_pull_accounts[@]}"; do
    echo "Downloading for: $yt_account"
    download_url "https://www.youtube.com/$yt_account"

    while read -r playlist_details; do
        playlist_url=$(echo "$playlist_details" | jq -r .url)
        playlist_title=$(echo "$playlist_details" | jq -r .title)

        echo "Updating playlist: $playlist_title - $playlist_url"
        yt-dlp \
            -o "$yt_account/Playlists/%(playlist)s/%(playlist_autonumber)s - %(title)s [%(id)s].%(ext)s" \
            --playlist-reverse \
            --abort-on-error \
            --write-info-json \
            --download-archive archive.txt \
            --remote-components ejs:github \
            --js-runtimes node \
            --cookies "~/Downloads/cookies.txt" \
            -t sleep \
            -t mkv \
            "$playlist_url";
        # yt-dlp does some parsing fuckery when a path contains a colon
        # this just tries to work around that by grabbing the existing path
        # created from the above yt-dlp call
        playlist_path=$(find "./$yt_account/Playlists" -type d -name "$(echo "$playlist_title" | sed -E "s|(.*?):.*?|\1|")*" -print | head -n 1)
        [ -z "$playlist_path" ] && echo "Failed to properly get playlist path. Exiting early" && exit 1
        if ! echo "#EXTM3U" > "$playlist_path/$playlist_title.m3u"; then
            echo "failed to write m3u. Exiting early"
            exit 1
        fi
        # yt-dlp doesn't really give us a decent way to do this...
        # so instead we're gonna do some bullshit
        while read -r playlist_video_id; do
            find . -type f -name "*\[$playlist_video_id\].mkv" | sed -E "s|^./|../../../|" >> "$playlist_path/$playlist_title.m3u"
        done < <(yt-dlp --flat-playlist -j "$playlist_url" 2>/dev/null | jq -r .id)
    done < <(yt-dlp --flat-playlist -j "https://www.youtube.com/$yt_account/playlists" 2>/dev/null | jq -c "{url: .url,title: .title}")
done
