#!/bin/sh
#
# bd - move back up the directory tree to the first directory matching the name

usage() {
  printf %s "\
  $(basename "$0")
    a simple script go back to a specified directory up in the hierarchy

  usage:
    If you are in this path /home/user/project/src/org/main/site/utils/file/reader
    and you want to go to site directory quickly, then just type:
        . bd site
    If there are more than one directories with same name up in the hierarchy,
    bd will take you to the closest.

    If you dont want to type the full directory name, then you can use
    the -s switch (meaning starts with) and just give the starting few characters
        . bd -s si

  tip:
    To get the most out of it, put this line:
        alias bd='. bd -s'
"
  exit 0
}

if [ $# -eq 0 ]; then
  usage
else
  OLDPWD=$(pwd)

  if [ "$1" = "-s" ]; then
    NEWPWD=$(echo "${OLDPWD}" | sed 's|\(.*/'"$2"'[^/]*/\).*|\1|')
    index=$(echo "${NEWPWD}" | awk '{ print index($1,"/'"$2"'"); }')
  else
    NEWPWD=$(echo "${OLDPWD}" | sed 's|\(.*/'"$1"'/\).*|\1|')
    index=$(echo "${NEWPWD}" | awk '{ print index($1,"/'"$1"'/"); }')
  fi

  if [ "${index}" -eq 0 ]; then
    echo "No such occurrence."
  fi

  echo "${NEWPWD}"
  cd "${NEWPWD}" || return 1
fi

# ----------------------------------------------------------------------------
bd() {

  # Check arguments; default to ".."
  if [ "$#" -gt 1 ]; then
    printf >&2 'bd(): Too many arguments\n'
    return 2
  fi
  set -- "${1:-..}"

  # Look at argument given; default to going up one level
  case $1 in

    # If it's slash, dot, or dot-dot, we'll just go there, like `cd` would
    / | . | ..) ;;

    # Anything else with a slash anywhere is an error
    */*)
      printf >&2 'bd(): Illegal slash\n'
      return 2
      ;;

    # Otherwise, add and keep chopping at the current directory until it's
    # empty or it matches the request, then shift the request off
    *)
      set -- "$1" "${PWD}"
      while :; do
        case $2 in
          */"$1" | '') break ;;
          */) set -- "$1" "${2%/}" ;;
          */*) set -- "$1" "${2%/*}" ;;
          *) set -- "$1" '' ;;
        esac
      done
      shift
      ;;
  esac

  # If we have nothing to change into, there's an error
  if [ -z "$1" ]; then
    printf >&2 'bd(): No match\n'
    return 1
  fi

  # We have a match; try and change into it
  # shellcheck disable=SC2164
  cd -- "$1"
}
