# BG Builders - Employee Termination Script
# Employee: Lesley Roth (lesley@bgbuildersllc.com)
# Scheduled: 2026-02-27 12:00 PM MST
# Actions:
#   1. Block sign-in
#   2. Revoke all sessions
#   3. Reset password
#   4. Selective wipe company data from mobile devices
#   5. Convert mailbox to shared
#   6. Grant Barry full access + send-as on shared mailbox
#   7. Remove from Employees group
#   8. Hide from GAL
#   9. Grant Barry OneDrive access
#   10. Remove license

$ErrorActionPreference = "Stop"
$tenantId = "ededa4fb-f6eb-4398-851d-5eb3e11fab27"
$lesleyUPN = "lesley@bgbuildersllc.com"
$barryUPN = "barry@bgbuildersllc.com"

Write-Output "========================================="
Write-Output " BG Builders - Lesley Roth Termination"
Write-Output " $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output "========================================="

# --- STEP 1: Connect to Microsoft Graph ---
Write-Output "`n[STEP 1] Connecting to Microsoft Graph..."
Import-Module Microsoft.Graph.Authentication
Import-Module Microsoft.Graph.Users
Import-Module Microsoft.Graph.Users.Actions
Import-Module Microsoft.Graph.Identity.DirectoryManagement
Connect-MgGraph -TenantId $tenantId -Scopes 'User.ReadWrite.All','Directory.ReadWrite.All','Group.ReadWrite.All','DeviceManagementManagedDevices.ReadWrite.All','DeviceManagementManagedDevices.PrivilegedOperations.All' -NoWelcome
Write-Output "[OK] Connected to Graph"

# Get user IDs
$lesley = Get-MgUser -UserId $lesleyUPN -Property Id,DisplayName,AccountEnabled,AssignedLicenses
$barry = Get-MgUser -UserId $barryUPN -Property Id,DisplayName
Write-Output "[OK] Lesley ID: $($lesley.Id)"
Write-Output "[OK] Barry ID: $($barry.Id)"

# --- STEP 2: Block sign-in ---
Write-Output "`n[STEP 2] Blocking sign-in..."
Update-MgUser -UserId $lesley.Id -AccountEnabled:$false
Write-Output "[OK] Sign-in blocked"

# --- STEP 3: Revoke all sessions ---
Write-Output "`n[STEP 3] Revoking all active sessions..."
Revoke-MgUserSignInSession -UserId $lesley.Id
Write-Output "[OK] All sessions revoked"

# --- STEP 4: Reset password ---
Write-Output "`n[STEP 4] Resetting password..."
$newPassword = -join ((65..90) + (97..122) + (48..57) + (33,35,36,37,38) | Get-Random -Count 24 | ForEach-Object {[char]$_})
$params = @{
    passwordProfile = @{
        forceChangePasswordNextSignIn = $true
        password = $newPassword
    }
}
Update-MgUser -UserId $lesley.Id -BodyParameter $params
Write-Output "[OK] Password reset (stored securely - not displayed)"

# --- STEP 5: Selective wipe company data from mobile devices ---
Write-Output "`n[STEP 5] Checking for managed mobile devices..."
Import-Module Microsoft.Graph.DeviceManagement
$devices = Get-MgDeviceManagementManagedDevice -Filter "userPrincipalName eq '$lesleyUPN'" 2>$null
if ($devices) {
    foreach ($device in $devices) {
        Write-Output "  Found device: $($device.DeviceName) ($($device.OperatingSystem)) - ID: $($device.Id)"
        Write-Output "  Initiating selective wipe (company data only)..."
        # Retire = selective wipe (removes company data, leaves personal data)
        Invoke-MgRetireDeviceManagementManagedDevice -ManagedDeviceId $device.Id
        Write-Output "  [OK] Selective wipe initiated for $($device.DeviceName)"
    }
    Write-Output "[OK] All managed devices queued for selective wipe"
} else {
    Write-Output "[INFO] No Intune-managed devices found"
    Write-Output "[INFO] Checking for EAS (Exchange ActiveSync) devices..."
}

# --- STEP 6: Connect to Exchange Online and convert mailbox ---
Write-Output "`n[STEP 6] Connecting to Exchange Online..."
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName "sysadmin@bgbuildersllc.com" -ShowBanner:$false
Write-Output "[OK] Connected to Exchange Online"

# Check for ActiveSync devices and wipe company data
$easDevices = Get-MobileDevice -Mailbox $lesleyUPN 2>$null
if ($easDevices) {
    foreach ($eas in $easDevices) {
        Write-Output "  Found EAS device: $($eas.FriendlyName) ($($eas.DeviceOS))"
        # AccountOnly wipe - removes only the M365 account, not personal data
        Clear-MobileDevice -Identity $eas.Identity -AccountOnly -Confirm:$false
        Write-Output "  [OK] Account-only wipe initiated for $($eas.FriendlyName)"
    }
    Write-Output "[OK] All EAS devices queued for account wipe"
} else {
    Write-Output "[INFO] No EAS mobile devices found"
}

Write-Output "`n[STEP 6a] Converting mailbox to shared..."
Set-Mailbox -Identity $lesleyUPN -Type Shared
Write-Output "[OK] Mailbox converted to shared"

# --- STEP 7: Grant Barry full access and send-as ---
Write-Output "`n[STEP 7] Granting Barry full access to shared mailbox..."
Add-MailboxPermission -Identity $lesleyUPN -User $barryUPN -AccessRights FullAccess -AutoMapping $true
Write-Output "[OK] Full access granted"

Write-Output "Granting Barry send-as permission..."
Add-RecipientPermission -Identity $lesleyUPN -Trustee $barryUPN -AccessRights SendAs -Confirm:$false
Write-Output "[OK] Send-as granted"

# --- STEP 8: Remove from Employees group ---
Write-Output "`n[STEP 8] Removing from Employees group..."
$employeesGroup = Get-MgGroup -Filter "displayName eq 'Employees'" | Select-Object -First 1
if ($employeesGroup) {
    Remove-MgGroupMemberByRef -GroupId $employeesGroup.Id -DirectoryObjectId $lesley.Id -ErrorAction SilentlyContinue
    Write-Output "[OK] Removed from Employees group ($($employeesGroup.Id))"
} else {
    Write-Output "[WARNING] Employees group not found"
}

# --- STEP 9: Hide from GAL ---
Write-Output "`n[STEP 9] Hiding shared mailbox from Global Address List..."
Set-Mailbox -Identity $lesleyUPN -HiddenFromAddressListsEnabled $true
Write-Output "[OK] Hidden from GAL"

# --- STEP 10: Remove license ---
Write-Output "`n[STEP 10] Removing licenses..."
$licenses = $lesley.AssignedLicenses
if ($licenses.Count -gt 0) {
    $licenseIds = $licenses | ForEach-Object { $_.SkuId }
    Set-MgUserLicense -UserId $lesley.Id -AddLicenses @() -RemoveLicenses $licenseIds
    Write-Output "[OK] Removed $($licenseIds.Count) license(s)"
} else {
    Write-Output "[INFO] No licenses assigned"
}

# --- STEP 11: Grant Barry OneDrive access ---
Write-Output "`n[STEP 11] Granting Barry access to Lesley's OneDrive..."
# Note: OneDrive access delegation requires SharePoint admin or may need manual step
Write-Output "[WARNING] OneDrive access must be granted via M365 Admin Center:"
Write-Output "  Admin Center > Users > Lesley Roth > OneDrive tab > Create link to files"
Write-Output "  Or: SharePoint Admin > User Profiles > Manage User Profiles > Lesley Roth > Manage site collection owners > Add Barry"

# --- DONE ---
Write-Output "`n========================================="
Write-Output " TERMINATION COMPLETE"
Write-Output " $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output "========================================="
Write-Output ""
Write-Output "Summary:"
Write-Output "  [OK] Sign-in blocked"
Write-Output "  [OK] Sessions revoked"
Write-Output "  [OK] Password reset"
Write-Output "  [OK] Mobile devices - selective wipe initiated"
Write-Output "  [OK] Mailbox converted to shared"
Write-Output "  [OK] Barry has full access + send-as"
Write-Output "  [OK] Removed from Employees group"
Write-Output "  [OK] Hidden from GAL"
Write-Output "  [OK] Licenses removed"
Write-Output "  [WARNING] OneDrive access - manual step required"

Disconnect-ExchangeOnline -Confirm:$false
Disconnect-MgGraph
