#!/usr/bin/env bash
# .NET and NuGet capability detection and updates.

ensure_dotnet_outdated() {
  local tool="$ROOT/.maintenance/tools/dotnet-outdated" bin="$ROOT/.maintenance/tools/dotnet-outdated/dotnet-outdated"
  [[ -x "$bin" ]] && { printf '%s\n' "$bin"; return; }
  if ((DRY_RUN)); then printf '%s\n' "$bin"; return; fi
  mkdir -p "$tool"
  dotnet tool install dotnet-outdated-tool --tool-path "$tool" >>"$LOG_DIR/commands.log" 2>&1 || return 1
  printf '%s\n' "$bin"
}

update_dotnet() {
  ((${#DOTNET_PROJECTS[@]})) || return 0
  has dotnet || { err 'dotnet is unavailable.'; return 1; }
  create_backup
  local project dir tool lock
  for project in "${DOTNET_PROJECTS[@]}"; do
    dir="$(dirname "$project")"
    if dotnet package update --help >/dev/null 2>&1 && [[ "$MODE" == latest || "$MODE" == semver-safe ]]; then
      run "Update NuGet packages: ${project#$ROOT/}" "$dir" dotnet package update --project "$project" || true
    else
      tool="$(ensure_dotnet_outdated || true)"
      [[ -n "$tool" ]] || { err 'dotnet-outdated could not be provisioned.'; continue; }
      lock=None; [[ "$MODE" == minor ]] && lock=Major; [[ "$MODE" == patch || "$MODE" == semver-safe ]] && lock=Minor
      if [[ "$MODE" == interactive ]]; then
        run 'Update NuGet packages interactively' "$dir" "$tool" "$project" --upgrade:Prompt --pre-release Never --version-lock "$lock" || true
      else
        run 'Update NuGet packages' "$dir" "$tool" "$project" --upgrade --pre-release Never --version-lock "$lock" || true
      fi
    fi
    run 'dotnet restore with NuGet audit' "$dir" dotnet restore "$project" -p:NuGetAudit=true -p:NuGetAuditMode=all -p:NuGetAuditLevel=moderate || true
  done
}
