#!/usr/bin/env bash
#
# nexus_component_count
#
# Lists all repositories in a Nexus instance and counts the number of components in each.
# Requires environment variables NEXUS_HOST and NEXUS_PASSWORD.

#set -euo pipefail
set -uo pipefail

# --- Validate environment variables ---
if [[ -z "${NEXUS_HOST:-}" ]]; then
  echo "Error: Environment variable NEXUS_HOST must be set" >&2
  exit 1
fi

if [[ -z "${NEXUS_PASSWORD:-}" ]]; then
  echo "Error: Environment variable NEXUS_PASSWORD must be set" >&2
  exit 1
fi

# --- Main loop ---
curl -su "admin:$NEXUS_PASSWORD" https://nexus.ellisbs.co.uk/service/rest/v1/repositories 2>/dev/null\
| jq -r '.[].name'\
| while read -r repo; do
  count=0
  continuationToken=null
  while :; do
    resp=$(curl -su "admin:$NEXUS_PASSWORD" "https://nexus.ellisbs.co.uk/service/rest/v1/components?repository=$repo${continuationToken:+&continuationToken=$continuationToken}" 2>/dev/null)
    c=$(echo "$resp" | jq '.items | length' 2>/dev/null)
    count=$((count + c))
    continuationToken=$(echo "$resp" | jq -r '.continuationToken' 2>/dev/null)
    [ "$continuationToken" = "null" ] && break
  done
  printf "%-30s %5d components\n" "$repo" "$count"
done | grep components 2>/dev/null
