#!/bin/sh

init_variables() {
  progname=${0##*/}

  PROJECTS_DIR="${PROJECTS_DIR:-${HOME}/projects}"

  TYPE=
  PROJECT=
}

parse_command_line() {
  TYPE="$1"
  PROJECT="$2"
}

validate_command_line() {
  if [ -z "${TYPE}" ]; then
    exit_error "[type: main|repo] [name]"
    # exit_error 'Missing type argument'
  fi

  if [ "${TYPE}" != 'main' ] \
    && [ "${TYPE}" != 'repo' ]; then
    exit_error "Invalid type '${TYPE}'"
  fi
}

exit_error() {
  [ -z "$1" ] || echo "${progname}: $1"
  exit 1
} >&2

# shellcheck disable=SC2249
get_project_path() {
  case "${TYPE}" in
    main)
      find "${PROJECTS_DIR}"/* \
        -type d -prune -name "${PROJECT}"
      ;;
    repo)
      find "${PROJECTS_DIR}"/*/* \
        -type d -prune -name "${PROJECT}"
      ;;
  esac
}

# shellcheck disable=SC2249
get_type_path() {
  case "${TYPE}" in
    main) echo "${PROJECTS_DIR}" ;;
    repo) echo "${PROJECTS_DIR}" ;;
  esac
}

display_path() {
  if [ -n "${PROJECT}" ]; then
    PROJECT_PATH="$(get_project_path)"
  else
    PROJECT_PATH="$(get_type_path)"
  fi

  if [ -z "${PROJECT_PATH}" ]; then
    echo 'No such project path' >&2
    return 1
  fi

  echo "${PROJECT_PATH}"
}

init_variables
parse_command_line "$@"
validate_command_line

display_path
