#!/usr/bin/env bash
###############################################################################
# __                _
# \ \   _ __   ___ | |_ ___  ___
#  \ \ | '_ \ / _ \| __/ _ \/ __|
#  / / | | | | (_) | ||  __/\__ \
# /_/  |_| |_|\___/ \__\___||___/
#
# `notes`
#
# Part of:
# __          _
# \ \   _ __ | |__
#  \ \ | '_ \| '_ \
#  / / | | | | |_) |
# /_/  |_| |_|_.__/
#
# [nb] Command line and local web note-taking, bookmarking, and archiving with
# plain text data storage, encryption, filtering and search, pinning, #tagging,
# Git-backed versioning and syncing, Pandoc-backed conversion, global and local
# notebooks, customizable color themes, [[wiki-style linking]], plugins, and
# more in a single portable, user-friendly script.
#
# https://github.com/xwmx/nb
#
# Based on Bash Boilerplate: https://github.com/xwmx/bash-boilerplate
#
# Copyright (c) 2015-present William Melody • hi@williammelody.com
# AGPLv3 • See LICENSE for details.
###############################################################################

export _NB_PATH="${_NB_PATH:-}"

if [[ -z "${_NB_PATH:-}" ]]
then
  _NB_PATH="$(command -v nb)"
fi

if [[ -z "${_NB_PATH:-}" ]]
then
  cat <<HEREDOC
\`notes\` is part of \`nb\`. To install \`nb\`, see:
  https://github.com/xwmx/nb
HEREDOC
fi

_main() {
  if [[ "${1:-}" =~ ^-h$|^--help$|^h$|^help$ ]] ||
     {
       [[ "${1:-}" =~ ^q$|^search$ ]] && [[ -z "${2:-}" ]]
     }
  then
    {

      shift

      {
        if [[ -n "${*:-}" ]]
        then
          "${_NB_PATH:-}" help "${@}"
        else
          cat <<HEREDOC
  __                _
  \ \   _ __   ___ | |_ ___  ___
   \ \ | '_ \ / _ \| __/ _ \/ __|
   / / | | | | (_) | ||  __/\__ \\
  /_/  |_| |_|\___/ \__\___||___/

 Part of [nb]
HEREDOC
          "${_NB_PATH:-}" help | sed -e '1,6d'

        fi
      } | sed -e "s/^  nb$/  notes/g"         \
        | sed -e "s/  nb /  notes /g"         \
        | sed -e "s/\`nb/\`notes/g"           \
        | sed -e "s/^\`notes\`/\`nb\`/g"      \
        | sed -E "s/nb(.*Command)/notes\1/g"  \
        | sed -e '$ d'

      cat <<HEREDOC
------------------------------------------
Part of \`nb\` (https://github.com/xwmx/nb).
For more information, see: \`nb help\`.
HEREDOC
    } | if [[ -n "${PAGER:-}" ]] && [[ ! "${PAGER:-}" =~ less ]]
        then
          "${PAGER}"
        elif hash "less" 2>/dev/null
        then
          less              \
            --CLEAR-SCREEN  \
            --prompt="> scroll for more, h for help, or q to quit"
        else
          cat
        fi
  else
    "${_NB_PATH}" "${@:-}"
  fi
} && _main "${@:-}"
