#!/usr/bin/env bash

hypertwist_sentrux_repo_root() {
  cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd
}

hypertwist_resolve_sentrux_command() {
  local repo_root="${1:-$(hypertwist_sentrux_repo_root)}"
  local repo_local_sentrux_binary="$repo_root/sentrux"
  local repo_local_sentrux_windows_binary="$repo_root/sentrux.exe"
  local repo_tools_sentrux_binary="$repo_root/tools/sentrux/bin/sentrux"
  local repo_tools_sentrux_windows_binary="$repo_root/tools/sentrux/bin/sentrux.exe"
  local bootstrap_script="$repo_root/scripts/bootstrap-hypertwist-sentrux.sh"

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

  if [[ -x "$repo_local_sentrux_binary" ]]; then
    printf '%s\n' "$repo_local_sentrux_binary"
    return 0
  fi

  if [[ -x "$repo_local_sentrux_windows_binary" ]]; then
    printf '%s\n' "$repo_local_sentrux_windows_binary"
    return 0
  fi

  if [[ -x "$repo_tools_sentrux_binary" ]]; then
    printf '%s\n' "$repo_tools_sentrux_binary"
    return 0
  fi

  if [[ -x "$repo_tools_sentrux_windows_binary" ]]; then
    printf '%s\n' "$repo_tools_sentrux_windows_binary"
    return 0
  fi

  if [[ -x "$bootstrap_script" ]]; then
    "$bootstrap_script" --if-missing >/dev/null 2>&1 || true
  fi

  if [[ -x "$repo_tools_sentrux_binary" ]]; then
    printf '%s\n' "$repo_tools_sentrux_binary"
    return 0
  fi

  if [[ -x "$repo_tools_sentrux_windows_binary" ]]; then
    printf '%s\n' "$repo_tools_sentrux_windows_binary"
    return 0
  fi

  if command -v sentrux >/dev/null 2>&1; then
    printf 'sentrux\n'
    return 0
  fi

  return 1
}

hypertwist_populate_sentrux_source_only_root() {
  local repo_root="$1"
  local temp_root="$2"

  mkdir -p "$temp_root/.sentrux"
  cp "$repo_root/.sentrux/rules.toml" "$temp_root/.sentrux/rules.toml"

  local copy_targets=(
    "UnrealHyperTwist/Source"
    "Content/Browser/src"
    "website/src"
    "website/server/src"
    "scripts"
  )

  local target=""
  for target in "${copy_targets[@]}"; do
    local source_path="$repo_root/$target"
    if [[ ! -e "$source_path" ]]; then
      continue
    fi

    local destination_path="$temp_root/$target"
    mkdir -p "$(dirname "$destination_path")"
    cp -R "$source_path" "$destination_path"
  done
}
