#!/usr/bin/env bash
set -eo pipefail

# Download music from Youtube or Youtube Music
# and save as top quality flac file without video
# Playlist and video/track URLs are supported
# Usage:     $ ytmusic https://www.youtube.com/watch?v=dQw4w9WgXcQ
# More info: https://github.com/ytdl-org/youtube-dl

if [[ "$1" == "-h" || "$1" == "--help" ]]; then
    cat <<EOF
Usage: $(basename "$0") [-h] <url>

Download music from YouTube or YouTube Music as FLAC.

Options:
    -h, --help    Show this help message

Arguments:
    url           YouTube or YouTube Music URL (playlist or video)

Output:
    $HOME/ytmusic/<playlist>/<channel> - <title>.flac

EOF
    exit 0
fi

DEST_PATH="${HOME}/ytmusic"
mkdir -p "${DEST_PATH}"

youtube-dl \
    --extract-audio \
    --audio-format flac \
    --audio-quality 0 \
    --format bestaudio \
    --write-info-json \
    --output "${DEST_PATH}/%(playlist_title)s/%(channel)s - %(title)s.%(ext)s" \
    "$@"
