#!/usr/bin/env bash
#
# shelf - manage `$BOOK_DIR` `$PAPER_DIR`
# dependencies: fzf
#
# ---
# source: https://github.com/terror/dotfiles

# shellcheck shell=bash disable=SC2292,SC2312

directories="${BOOK_DIR-} ${PAPER_DIR-}"
results=""

for dir in ${directories}; do
  if [ -d "${dir}" ]; then
    if [ -z "${results}" ]; then
      results=$(fd . "${dir}" -d 1 | sed "s|^${dir}/||")
    else
      # results+=$'\n'$(fd . "${dir}" -d 1 | sed "s|^${dir}/||")
      results="${results}$'\n'$(fd . "${dir}" -d 1 | sed "s|^${dir}/||")"
    fi
  else
    printf '%s\n' "Warning: directory \`${dir}\` does not exist, skipping..." >&2
  fi
done

if [ -n "${results}" ]; then
  if command -v fzf >/dev/null 2>&1; then
    selected=$(echo "${results}" | fzf)
  fi

  if [ -n "${selected}" ]; then
    for dir in ${directories}; do
      full_path="${dir}/${selected}"

      if [ -e "${full_path}" ]; then
        open "${full_path}"
        exit 0
      fi
    done

    printf '%s\n' "Error: Could not find the full path of the selected file"
  else
    printf '%s\n' "No file selected"
  fi
else
  echo "error: no valid directories to search"
fi
