# Add Rob Williams and Howard to all GDAP Security Groups
# This fixes CIPP access issues for multiple users

$ErrorActionPreference = "Stop"

# Configuration
$TenantId = "ce61461e-81a0-4c84-bb4a-7b354a9a356d"
$ClientId = "fabb3421-8b34-484b-bc17-e46de9703418"
$ClientSecret = "~QJ8Q~NyQSs4OcGqHZyPrA2CVnq9KBfKiimntbMO"

# Users to add to GDAP groups
$UsersToAdd = @(
    "rob@azcomputerguru.com",
    "howard@azcomputerguru.com"
)

# GDAP Groups (from analysis)
$GdapGroups = @(
    @{Name="M365 GDAP Cloud App Security Administrator"; Id="009e46ef-3ffa-48fb-9568-7e8cb7652200"},
    @{Name="M365 GDAP Application Administrator"; Id="16e99bf8-a0bc-41d3-adf7-ce89310cece5"},
    @{Name="M365 GDAP Teams Administrator"; Id="35fafd80-498c-4c62-a947-ea230835d9f1"},
    @{Name="M365 GDAP Security Administrator"; Id="3ca0d8b1-a6fc-4e77-a955-2a7d749d27b4"},
    @{Name="M365 GDAP Privileged Role Administrator"; Id="49b1b90d-d7bf-4585-8fe2-f2a037f7a374"},
    @{Name="M365 GDAP Cloud Device Administrator"; Id="8e866fc5-c4bd-4ce7-a273-385857a4f3b4"},
    @{Name="M365 GDAP Exchange Administrator"; Id="92401e16-c217-4330-9bbd-6a978513452d"},
    @{Name="M365 GDAP User Administrator"; Id="baf461df-c675-4f9e-a4a3-8f03c6fe533d"},
    @{Name="M365 GDAP Privileged Authentication Administrator"; Id="c593633a-2957-4069-ae7e-f862a0896b67"},
    @{Name="M365 GDAP Intune Administrator"; Id="daad8ec5-d044-4d4c-bae7-5df98a637c95"},
    @{Name="M365 GDAP SharePoint Administrator"; Id="fa55c8c1-34e3-46b7-912e-f4d303081a82"},
    @{Name="M365 GDAP Authentication Policy Administrator"; Id="fdf38f92-8dd1-470d-8ce8-58f663235789"},
    @{Name="AdminAgents"; Id="ecc00632-9de6-4932-a62b-de57b72c1414"}
)

Write-Host "[INFO] Authenticating to Microsoft Graph..." -ForegroundColor Cyan

# Get access token
$TokenBody = @{
    client_id     = $ClientId
    client_secret = $ClientSecret
    scope         = "https://graph.microsoft.com/.default"
    grant_type    = "client_credentials"
}

$TokenResponse = Invoke-RestMethod -Method Post `
    -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" `
    -Body $TokenBody

$Headers = @{
    Authorization = "Bearer $($TokenResponse.access_token)"
}

Write-Host "[OK] Authenticated successfully" -ForegroundColor Green
Write-Host ""

# Process each user
$TotalSuccessCount = 0
$TotalSkippedCount = 0
$TotalErrorCount = 0

foreach ($UserUpn in $UsersToAdd) {
    Write-Host "="*80 -ForegroundColor Cyan
    Write-Host "PROCESSING USER: $UserUpn" -ForegroundColor Cyan
    Write-Host "="*80 -ForegroundColor Cyan

    # Get user ID
    Write-Host "[INFO] Looking up user..." -ForegroundColor Cyan
    try {
        $User = Invoke-RestMethod -Method Get `
            -Uri "https://graph.microsoft.com/v1.0/users/$UserUpn" `
            -Headers $Headers

        Write-Host "[OK] Found user:" -ForegroundColor Green
        Write-Host "  Display Name: $($User.displayName)"
        Write-Host "  UPN: $($User.userPrincipalName)"
        Write-Host "  ID: $($User.id)"
        Write-Host ""

        $UserId = $User.id
    }
    catch {
        Write-Host "[ERROR] User not found: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host ""
        continue
    }

    # Add user to each group
    $SuccessCount = 0
    $SkippedCount = 0
    $ErrorCount = 0

    foreach ($Group in $GdapGroups) {
        Write-Host "[INFO] Adding to: $($Group.Name)" -ForegroundColor Cyan

        # Check if already a member
        try {
            $Members = Invoke-RestMethod -Method Get `
                -Uri "https://graph.microsoft.com/v1.0/groups/$($Group.Id)/members" `
                -Headers $Headers

            $IsMember = $Members.value | Where-Object { $_.id -eq $UserId }

            if ($IsMember) {
                Write-Host "[SKIP] Already a member" -ForegroundColor Yellow
                $SkippedCount++
                continue
            }
        }
        catch {
            Write-Host "[WARNING] Could not check membership: $($_.Exception.Message)" -ForegroundColor Yellow
        }

        # Add to group
        try {
            $Body = @{
                "@odata.id" = "https://graph.microsoft.com/v1.0/directoryObjects/$UserId"
            } | ConvertTo-Json

            Invoke-RestMethod -Method Post `
                -Uri "https://graph.microsoft.com/v1.0/groups/$($Group.Id)/members/`$ref" `
                -Headers $Headers `
                -Body $Body `
                -ContentType "application/json" | Out-Null

            Write-Host "[SUCCESS] Added to group" -ForegroundColor Green
            $SuccessCount++
        }
        catch {
            Write-Host "[ERROR] Failed to add: $($_.Exception.Message)" -ForegroundColor Red
            $ErrorCount++
        }

        Start-Sleep -Milliseconds 500  # Rate limiting
    }

    # User summary
    Write-Host ""
    Write-Host "Summary for $($User.displayName):" -ForegroundColor Cyan
    Write-Host "  Successfully added:  $SuccessCount groups" -ForegroundColor Green
    Write-Host "  Already member of:   $SkippedCount groups" -ForegroundColor Yellow
    Write-Host "  Errors:              $ErrorCount groups" -ForegroundColor $(if($ErrorCount -gt 0){"Red"}else{"Green"})
    Write-Host ""

    $TotalSuccessCount += $SuccessCount
    $TotalSkippedCount += $SkippedCount
    $TotalErrorCount += $ErrorCount
}

Write-Host ""
Write-Host "="*80 -ForegroundColor Cyan
Write-Host "FINAL SUMMARY" -ForegroundColor Cyan
Write-Host "="*80 -ForegroundColor Cyan
Write-Host "Total users processed: $($UsersToAdd.Count)"
Write-Host "Total additions:       $TotalSuccessCount groups" -ForegroundColor Green
Write-Host "Total already members: $TotalSkippedCount groups" -ForegroundColor Yellow
Write-Host "Total errors:          $TotalErrorCount groups" -ForegroundColor $(if($TotalErrorCount -gt 0){"Red"}else{"Green"})
Write-Host ""

if ($TotalSuccessCount -gt 0 -or $TotalSkippedCount -gt 0) {
    Write-Host "[OK] Users should now be able to access all client tenants through CIPP!" -ForegroundColor Green
    Write-Host "[INFO] It may take 5-10 minutes for group membership to fully propagate." -ForegroundColor Cyan
    Write-Host "[INFO] Ask users to sign out of CIPP and sign back in." -ForegroundColor Cyan
}
else {
    Write-Host "[WARNING] Some operations failed. Review errors above." -ForegroundColor Yellow
}
