#!/usr/bin/env bash

source $IMPROMPTU_INTERNAL_BIN/utils
impromptu_ensure_constants

# Check for named subcommands (ignoring flags).
if [[ -n "$1" && $1 != -* ]]; then
  potential_subcommand="impromptu-$1"
  potential_bin_subcommand_path="$IMPROMPTU_BIN/$potential_subcommand"
  potential_internal_subcommand_path="$IMPROMPTU_INTERNAL_BIN/$potential_subcommand"

  # Check for the subcommand in impromptu's installed node modules.
  if [[ -x "$potential_subcommand_path" ]]; then
    subcommand="$potential_subcommand_path"
    shift

  elif [[ -x "$potential_internal_subcommand_path" ]]; then
    subcommand="$potential_internal_subcommand_path"
    shift

  # Check for the subcommand system-wide.
  elif command -v "$potential_subcommand" >/dev/null 2>&1; then
    subcommand="$potential_subcommand"
    shift
  fi
fi

# Check if we're looking for the version or help.
if [[ -z "$subcommand" && -n "$1" ]]; then
  if [[ "$1" == "-v" || "$1" == "--version" ]]; then
    subcommand="$IMPROMPTU_INTERNAL_BIN/impromptu-version"
  elif [[ "$1" == "-h" || "$1" == "--help" ]]; then
    subcommand="$IMPROMPTU_INTERNAL_BIN/impromptu-help"
  fi
fi

# If we couldn't find a matching subcommand, fall back to the defaults.
if [[ -z "$subcommand" ]]; then
  # If we're in an interactive shell, set prompt commands.
  if impromptu_in_interactive_shell; then
    subcommand="$IMPROMPTU_INTERNAL_BIN/impromptu-set-prompt"

  # Otherwise, just print the prompt.
  else
    subcommand="$IMPROMPTU_INTERNAL_BIN/impromptu-print"
  fi
fi

source $subcommand
