#!/bin/bash

OPTS=""
if [[ -n "$DEBUG" ]]
then
    set -x
else
    OPTS="-q"
fi

set -euo pipefail

if ! [[ -d /opt/mixcloud-downloader/venv ]]
then
    virtualenv -p python3 /opt/mixcloud-downloader/venv
fi

source /opt/mixcloud-downloader/venv/bin/activate

pip install --upgrade pip yt-dlp

errors=0

for i in Neosignal tasmo starkato b4m Alexeyan jakehunnter davem_dokebi tasmo
do
    echo "> mixcloud $i" >&2
    if ! [[ -d "/storage/nas/Musik/mixcloud/$i" ]]
    then
        # no -p here, this should fail if
        # zfs is not mounted
        mkdir "/storage/nas/Musik/mixcloud/$i"
    fi
    (
        cd "/storage/nas/Musik/mixcloud/$i"
        yt-dlp $OPTS "https://mixcloud.com/$i"
        echo $? >&2
    ) || errors=1
done

for i in CouchsofaLiveSets
do
    echo "> archive.org $i" >&2
    if ! [[ -d "/storage/nas/Musik/mixcloud/$i" ]]
    then
        # no -p here, this should fail if
        # zfs is not mounted
        mkdir "/storage/nas/Musik/mixcloud/$i"
    fi
    (
        cd "/storage/nas/Musik/mixcloud/$i"
        yt-dlp $OPTS "https://archive.org/details/$i"
        echo $? >&2
    ) || errors=1
done

for i in tschunkelmusik
do
    echo "> soundcloud $i" >&2
    if ! [[ -d "/storage/nas/Musik/mixcloud/$i" ]]
    then
        # no -p here, this should fail if
        # zfs is not mounted
        mkdir "/storage/nas/Musik/mixcloud/$i"
    fi
    (
        cd "/storage/nas/Musik/mixcloud/$i"
        yt-dlp $OPTS "https://soundcloud.com/$i"
        echo $? >&2
    ) || errors=1
done

exit $errors