#!/bin/bash
ARCHIVE="${HOME}/_library"

D1=$(find "${ARCHIVE}" -maxdepth 1 -type d -regextype posix-extended -regex "${ARCHIVE}/[0-9]-.*")
D2=$(find "${ARCHIVE}" -maxdepth 2 -type d -regextype posix-extended -regex "${ARCHIVE}/[0-9]+-[^/]+/[0-9]{3}-.*")
D3=$(find "${ARCHIVE}" -maxdepth 3 -type d -regextype posix-extended -regex "${ARCHIVE}/[0-9]+-[^/]+/[0-9]{3}-[^/]+/[0-9]{3}\.[0-9]{2}-.*")
D4=$(find "${ARCHIVE}" -maxdepth 4 -type d -regextype posix-extended -regex "${ARCHIVE}/[0-9]+-[^/]+/[0-9]{3}-[^/]+/[0-9]{3}\.[0-9]{2}-[^/]+/[0-9]{3}\.[0-9]{2}\.[a-zA-Z]+-.*")

if [ ! -z "$1" ]; then
    if [ "${#1}" = "1" ]; then
        target=$(printf "${D1}" | grep "$1")
    elif [ "${#1}" = "3" ]; then
        target=$(printf "${D2}" | grep "$1")
    elif [ "${#1}" = "6" ]; then
        target=$(printf "${D3}" | grep "$1")
    elif [ "${#1}" = "9" ]; then
        target=$(printf "${D4}" | grep "$1")
    fi
fi

if [ -z "$target" ]; then
    target=$(printf "${D1}\n${D2}\n${D3}\n${D4}" | fzf)
fi

if [ !  -z "$target" ]; then
    cd "$target"
fi
