#!/usr/bin/env bash

if [[ -n "${FORGE_SCOPE_HELPER_LOADED:-}" ]]; then
  return 0
fi

FORGE_SCOPE_HELPER_LOADED=1

forge_scope_repo_root() {
  local helper_dir
  helper_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

  if [[ -n "${PROJECT_ROOT:-}" ]]; then
    printf '%s\n' "$PROJECT_ROOT"
    return 0
  fi

  if [[ -n "${REPO_ROOT:-}" ]]; then
    printf '%s\n' "$REPO_ROOT"
    return 0
  fi

  printf '%s\n' "$(cd "$helper_dir/../.." && pwd)"
}

forge_scoped() {
  local root
  root="$(forge_scope_repo_root)"
  bash "$root/scripts/forge/scope.sh" "$@"
}

forge() {
  if [[ $# -gt 0 ]]; then
    case "$1" in
      build|test|script)
        local subcommand="$1"
        shift
        forge_scoped "$subcommand" "$@"
        return $?
        ;;
    esac
  fi

  command forge "$@"
}
