#!/usr/bin/env bash
# CyberTwin export recipe: the SLA Domains of a Rubrik Security Cloud account, as Rubrik returns them.
# Read-only: one sign-in, the slaDomains query (a GraphQL query, not a mutation), and the sign-out.
# Runs on your machine, writes local files, sends nothing to CyberTwin. Upload each
# rubrik-sla-domains*.json it writes.
#
# Steps read on 2026-11-11 in Rubrik's public API pages
# (https://github.com/rubrikinc/rubrik-api-documentation, api/auth and use-cases/slas, commit 91501f19):
# a service account's access token from its access token URI, the slaDomains query at
# https://<account>.my.rubrik.com/api/graphql, and DELETE /api/session. The members asked for are
# those of GlobalSlaReply in Rubrik's public schema (rubrikinc/rubrik-powershell-sdk,
# docs/graphql/schema-public.graphql, commit 558e3dd7). The answer names no account: the schema's root accountId is
# marked deprecated (ruling R31), so it is not asked for.
#
# Each file is one answer of the query as Rubrik returns it, printed by jq with two-space
# indentation: { "data": { "slaDomains": { "nodes": [...], "pageInfo": {...}, "count": n } } }.
# When the answer says hasNextPage, the next page is asked for with after: endCursor and written to
# its own file (rubrik-sla-domains-2.json and so on): each file is a whole answer.
#
# Needs: curl and jq. Usage: bash rubrik-sla-domains-export.sh <service-account.json>
# where <service-account.json> is the file "Download As JSON" gives when the service account is added.
set -euo pipefail
sa="${1:?give the service account file, e.g. bash rubrik-sla-domains-export.sh service-account.json}"
client_id=$(jq -r .client_id "$sa")
client_secret=$(jq -r .client_secret "$sa")
token_uri=$(jq -r .access_token_uri "$sa")
# The GraphQL address is on the host of the access token URI (Rubrik's pages use the same host for both).
host=$(printf '%s' "$token_uri" | sed -E 's#^(https://[^/]+)/.*#\1#')

token=$(curl -sS --fail --request POST --header "Content-Type: application/json" \
  --data "$(jq -n --arg id "$client_id" --arg s "$client_secret" '{client_id: $id, client_secret: $s}')" \
  "$token_uri" | jq -r .access_token)
unset client_secret
[ -n "$token" ] && [ "$token" != "null" ] || { echo "No access token: check the service account file." >&2; exit 1; }
trap 'curl -sS -X DELETE "$host/api/session" --header "Authorization: Bearer $token" --header "Content-type: application/json" > /dev/null || true' EXIT

read -r -d '' QUERY <<'GRAPHQL' || true
query SLADomains($after: String) {
  slaDomains(after: $after) {
    nodes {
      name
      id
      version
      ...GlobalSlaReplyFragment
    }
    pageInfo {
      endCursor
      hasNextPage
      __typename
    }
    count
    __typename
  }
  __typename
}

fragment GlobalSlaReplyFragment on GlobalSlaReply {
    id
    description
    isRetentionLockedSla
    retentionLockMode
    baseFrequency {
      duration
      unit
      __typename
    }
    ownerOrg {
      id
      name
      __typename
    }
    backupWindows {
      durationInHours
      startTimeAttributes {
        hour
        minute
        __typename
      }
      __typename
    }
    firstFullBackupWindows {
      durationInHours
      startTimeAttributes {
        dayOfWeek {
          day
          __typename
        }
        hour
        minute
        __typename
      }
      __typename
    }
    snapshotSchedule {
      ...SnapshotSchedulesForSlaDomainFragment
      __typename
    }
    localRetentionLimit {
      duration
      unit
      __typename
    }
    archivalSpecs {
      threshold
      thresholdUnit
      frequencies
      archivalLocationToClusterMapping {
        cluster {
          id
          name
          __typename
        }
        location {
          id
          name
          targetType
          __typename
        }
        __typename
      }
      storageSetting {
        id
        name
        groupType
        targetType
        targets {
          id
          name
          cluster {
            id
            name
            __typename
          }
          __typename
        }
        __typename
      }
      archivalTieringSpec {
        coldStorageClass
        shouldTierExistingSnapshots
        minAccessibleDurationInSeconds
        __typename
      }
      __typename
    }
    replicationSpecsV2 {
      ...DetailedReplicationSpecsV2ForSlaDomainFragment
      __typename
    }
    objectTypes
    isDefault
    __typename
  }

  fragment SnapshotSchedulesForSlaDomainFragment on SnapshotSchedule {
    minute {
      basicSchedule {
        frequency
        retention
        retentionUnit
        __typename
      }
      __typename
    }
    hourly {
      basicSchedule {
        frequency
        retention
        retentionUnit
        __typename
      }
      __typename
    }
    daily {
      basicSchedule {
        frequency
        retention
        retentionUnit
        __typename
      }
      __typename
    }
    weekly {
      basicSchedule {
        frequency
        retention
        retentionUnit
        __typename
      }
      dayOfWeek
      __typename
    }
    monthly {
      basicSchedule {
        frequency
        retention
        retentionUnit
        __typename
      }
      dayOfMonth
      __typename
    }
    quarterly {
      basicSchedule {
        frequency
        retention
        retentionUnit
        __typename
      }
      dayOfQuarter
      quarterStartMonth
      __typename
    }
    yearly {
      basicSchedule {
        frequency
        retention
        retentionUnit
        __typename
      }
      dayOfYear
      yearStartMonth
      __typename
    }
    __typename
  }

fragment DetailedReplicationSpecsV2ForSlaDomainFragment on ReplicationSpecV2 {
  replicationLocalRetentionDuration {
    duration
    unit
    __typename
  }
  cascadingArchivalSpecs {
    archivalTieringSpec {
      coldStorageClass
      shouldTierExistingSnapshots
      minAccessibleDurationInSeconds
      isInstantTieringEnabled
      __typename
    }
    archivalLocation {
      id
      name
      targetType
      ... on RubrikManagedAwsTarget {
        immutabilitySettings {
          lockDurationDays
          __typename
        }
        __typename
      }
      ... on RubrikManagedAzureTarget {
        immutabilitySettings {
          lockDurationDays
          __typename
        }
        __typename
      }
      ... on CdmManagedAwsTarget {
        immutabilitySettings {
          lockDurationDays
          __typename
        }
        __typename
      }
      ... on CdmManagedAzureTarget {
        immutabilitySettings {
          lockDurationDays
          __typename
        }
        __typename
      }
      ... on RubrikManagedRcsTarget {
        immutabilityPeriodDays
        syncStatus
        tier
        __typename
      }
      ... on RubrikManagedS3CompatibleTarget {
        immutabilitySetting {
          bucketLockDurationDays
          __typename
        }
        __typename
      }
      __typename
    }
    frequency
    archivalThreshold {
      duration
      unit
      __typename
    }
    __typename
  }
  retentionDuration {
    duration
    unit
    __typename
  }
  cluster {
    id
    name
    version
    __typename
  }
  targetMapping {
    id
    name
    targets {
      id
      name
      cluster {
        id
        name
        __typename
      }
      __typename
    }
    __typename
  }
  awsTarget {
    accountId
    accountName
    region
    __typename
  }
  azureTarget {
    region
    __typename
  }
  __typename
}
GRAPHQL

page=1
after=null
while :; do
  out="rubrik-sla-domains.json"
  [ "$page" -gt 1 ] && out="rubrik-sla-domains-$page.json"
  curl -sS --fail -X POST "$host/api/graphql" \
    --header "Authorization: Bearer $token" --header "Content-type: application/json" \
    --data "$(jq -n --arg q "$QUERY" --argjson after "$after" '{query: $q, variables: {after: $after}}')" \
    | jq . > "$out"
  if jq -e '.errors' "$out" > /dev/null; then echo "Rubrik answered with errors: see $out" >&2; exit 1; fi
  echo "Wrote $out."
  [ "$(jq -r '.data.slaDomains.pageInfo.hasNextPage' "$out")" = "true" ] || break
  after=$(jq '.data.slaDomains.pageInfo.endCursor' "$out")
  page=$((page + 1))
done
echo "Upload each rubrik-sla-domains*.json at /upload."
