I’m running a Plex Media Server instance and use it as a self-hosted music streaming service (like Spotify, Deezer, Apple Music).
These days, I get most of my music from bandcamp, so I regularly need to import bandcamp downloads into my Plex Media Server library.

Since doing this manually is error-prone and can get tedious, I wrote a little script that downloads and/or imports zip files from bandcamp into my Plex library.

The script automatically tries to guess the artist and album name from the zip file name, but prompts for confirmation/correction of these details.

The script is released as public domain under the Unlicense.

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

MUSIC_LIBRARY=./music

err() {
    echo "${1}" >&2
    exit 1
}

trim() {
	local str="${*}"

	str="${str#"${str%%[![:space:]]*}"}"
	str="${str%"${str##*[![:space:]]}"}"

	printf "%s" "${str}"
}

# Check dependencies
[[ -x "$(command -v curl)" ]] || err "cURL not found. Make sure that cURL is installed and in \$PATH"
[[ -x "$(command -v unzip)" ]] || err "unzip not found. Make sure that unzip is installed and in \$PATH"

# Ensure that a filename is given
if [[ ${#} -lt 1 ]] || [[ -z "${1}" ]]; then
	err "Please provide a zip file name or an URL to (download and) extract"
fi

file="${1}"
if [[ "${1}" =~ https://.* ]]; then
	curl -OJ "${1}"
	file="$(ls -t *.zip | head -1)"
fi

# Try to guess artist and album from the zip file name
guesses=0
IFS='-' read -ra parts <<< "${file}"
if [[ ${#parts[@]} -eq 2 ]]; then
	guesses=1
	artist_guess="$(trim "${parts[0]}")"
	album_guess="$(trim "${parts[1]%".zip"}")"
fi

# Read artist and album name
read -p "Artist (${artist_guess-}): " artist
read -p "Album (${album_guess-}): " album

if [[ ${guesses} -eq 1 ]]; then
	if [[ -z "${artist}" ]]; then
		artist="${artist_guess}"
	fi
	if [[ -z "${album}" ]]; then
		album="${album_guess}"
	fi
fi

dir="${MUSIC_LIBRARY}/${artist}/${album}"

# Create album dir if it does not exist
if [[ ! -d "${dir}" ]]; then
	mkdir -p "${dir}"
else
	err "Directory ${dir} does already exist"
fi

# Unzip music into directory
unzip "${file}" -d "${dir}"

rm "${file}"