#!/bin/bash

MNT_POINT="/mnt/e"
STORAGE="$MNT_POINT/Downloads/"
FORMAT="(bestvideo[vcodec^=av01][height>=1080][fps>30]/bestvideo[vcodec=vp9.2][height>=1080][fps>30]/bestvideo[vcodec=vp9][height>=1080][fps>30]/bestvideo[vcodec^=av01][height>=1080]/bestvideo[vcodec=vp9.2][height>=1080]/bestvideo[vcodec=vp9][height>=1080]/bestvideo[height>=1080]/bestvideo[vcodec^=av01][height>=720][fps>30]/bestvideo[vcodec=vp9.2][height>=720][fps>30]/bestvideo[vcodec=vp9][height>=720][fps>30]/bestvideo[vcodec^=av01][height>=720]/bestvideo[vcodec=vp9.2][height>=720]/bestvideo[vcodec=vp9][height>=720]/bestvideo[height>=720]/bestvideo)+(bestaudio[acodec=opus]/bestaudio)/best"
EXTENSION="mkv"
LIST_FILE=".ytdlb"
ARGS=("$@")
COOKIES=""

if [ ! -d "$MNT_POINT/" ]; then
        echo "Mount point does not exist: $MNT_POINT"
        exit 1
fi

if [ ! -d "$STORAGE" ]; then
    mkdir -p "$STORAGE"
fi

cd "$STORAGE" || exit

echo "Items: $#"

for VAR in "${ARGS[@]}"; do
        OUTPUT="[%(uploader)s] %(title).200s [%(upload_date)s - %(id)s].%(ext)s"

        if [[ $VAR == *"twitch.tv"* ]]; then
                OUTPUT="%(title).200s [%(upload_date)s - %(id)s].%(ext)s"
        fi

        if [[ $VAR == *"youtube.com"* ]]; then
                if [ -f "$STORAGE/cookies.txt" ]; then
                        COOKIES="--cookies cookies.txt"
                fi
        fi

    yt-dlp --limit-rate 7M --external-downloader=aria2c \
        --restrict-filenames \
        --extractor-args youtubetab:skip=authcheck \
        --download-archive "archive.log" -i --add-metadata \
        --all-subs $COOKIES --embed-subs --trim-filenames 200 \
        -o "$OUTPUT" --merge-output-format "$EXTENSION" \
        --format "$FORMAT" "$VAR"
done
