# Check if a user is currently logged on, if no user logged on the script exits
$quserOutput = quser 2>&1
if ($quserOutput -like '*No User exists for*') {
    exit
}

# Load required assemblies
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# Functions
#Function VPN Dialog Box
function Show-VPNDialog {
    # Create form
    $Form = New-Object System.Windows.Forms.Form
    $Form.Text = 'Connect VPN'
    $Form.Size = New-Object System.Drawing.Size(500, 150)
    $Form.StartPosition = 'CenterScreen'
    $Form.TopMost = $true

    # Create message label
    $MessageLabel = New-Object System.Windows.Forms.Label
    $MessageLabel.Location = New-Object System.Drawing.Point(10, 20)
    $MessageLabel.Size = New-Object System.Drawing.Size(420, 60)
    $MessageLabel.Text = "Please connect your Cisco AnyConnect VPN, Wait 30 seconds and then press OK.  The device will restart when process completed."
    $Form.Controls.Add($MessageLabel)

    # Create OK button
    $OKButton = New-Object System.Windows.Forms.Button
    $OKButton.Location = New-Object System.Drawing.Point(140, 60)
    $OKButton.Size = New-Object System.Drawing.Size(60, 40)
    $OKButton.Text = 'OK'
    $OKButton.Add_Click({
        # Check if Cisco AnyConnect is connected
        $vpnConnected = Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where-Object { $_.IPEnabled -eq $true -and $_.Description -like '*Cisco AnyConnect*' }
        if ($null -ne $vpnConnected) {
            $Form.Close()
        } else {
            [System.Windows.Forms.MessageBox]::Show("Please connect your Cisco AnyConnect VPN", "VPN Not Connected", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning)
        }
    })
    $Form.Controls.Add($OKButton)

    # Show form
    $Form.ShowDialog()
}

#Function - Reboot Dialog box with countdown timer
function Show-RebootDialog {
    param(
        [int]$CountdownSeconds = 120
    )

    # Create and display the form
    $Form = New-Object System.Windows.Forms.Form
    $Form.Text = 'Reboot'
    $Form.Size = New-Object System.Drawing.Size(300, 150)
    $Form.StartPosition = 'CenterScreen'
    $Form.TopMost = $true

    # Countdown label
    $CountdownLabel = New-Object System.Windows.Forms.Label
    $CountdownLabel.Location = New-Object System.Drawing.Point(10, 20)
    $CountdownLabel.Size = New-Object System.Drawing.Size(280, 20)
    $CountdownLabel.Text = "Rebooting in 2 minutes..."
    $Form.Controls.Add($CountdownLabel)

    # Reboot button
    $RebootButton = New-Object System.Windows.Forms.Button
    $RebootButton.Location = New-Object System.Drawing.Point(60, 60)
    $RebootButton.Size = New-Object System.Drawing.Size(200, 50)
    $RebootButton.Text = 'Reboot Now'
    $RebootButton.Add_Click({
        $Form.Close()
        Restart-Computer -Force
    })
    $Form.Controls.Add($RebootButton)

    # Start the countdown in a background job
    $RebootJob = Start-Job -ScriptBlock {
        Start-Sleep -Seconds $using:CountdownSeconds
        Restart-Computer -Force
    }

    # Show the form
    $Form.ShowDialog()

    # If the form is closed (e.g., via the Reboot Now button), stop the reboot job
    Stop-Job -Job $RebootJob
    Remove-Job -Job $RebootJob
}

# Check for connectivity to domain.local
$canConnectToCorp = $false
try {
    Test-Connection -ComputerName "domain.local" -Count 1 -ErrorAction Stop
    $canConnectToCorp = $true
} catch {
    $canConnectToCorp = $false
}

# If cannot connect to domain.local, check VPN
if (-not $canConnectToCorp) {
    # Check if Cisco AnyConnect is already connected
    $vpnConnected = Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where-Object { $_.IPEnabled -eq $true -and $_.Description -like '*Cisco AnyConnect*' }
    if ($null -eq $vpnConnected) {
        # Prompt the user to connect the VPN
        Show-VPNDialog
    }
}

# Check if the current computer name is correct
$currentComputerName = (Get-WmiObject -Class Win32_ComputerSystem).Name

# Check for both naming conventions
if ($currentComputerName -match '^[A-Za-z]{6}\d{6}$' -or $currentComputerName -match '^[A-Za-z]{4}-$') {
    # Check if the registry key exists, if not, create it
    if (!(Test-Path -Path "HKLM:\SOFTWARE\Client\Autopilot")) {
        New-Item -Path "HKLM:\SOFTWARE\Client\Autopilot" -Force
    }
    # Write a registry key value
    Set-ItemProperty -Path "HKLM:\SOFTWARE\Client\Autopilot" -Name "Rename" -Value 1
    exit
}

# Application () ID, tenant ID, and  secret
$appId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
$tenantId = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
$Secret = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"

# Get an OAuth token
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

$body = @{
    _id     = $appId
    scope         = "https://graph.microsoft.com/.default"
    _secret = $Secret
    grant_type    = "_credentials"
}

$response = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $body
$token = $response.access_token

# Get the device serial number
$serial = (Get-WmiObject -Query "SELECT * FROM Win32_Bios").SerialNumber

# Get the device's group tag from Azure AD
$uri = "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeviceIdentities?`$filter=contains(serialNumber, '$serial')"

$headers = @{
    Authorization = "Bearer $token"
}

$response = Invoke-RestMethod -Uri $uri -Headers $headers -Method Get

# Output the group tag
$groupTag = $response.value[0].groupTag

# If the group tag doesn't exist or is empty, exit with code 1
if (-not $groupTag) {
    exit 1
}

# Perform a rename of the device
Rename-Computer -NewName $groupTag -Force
Write-Host $groupTag

# Check if the registry key exists, if not, create it
if (!(Test-Path -Path "HKLM:\SOFTWARE\Client\Autopilot")) {
    New-Item -Path "HKLM:\SOFTWARE\Client\Autopilot" -Force
}

# Write a registry key value
Set-ItemProperty -Path "HKLM:\SOFTWARE\Client\Autopilot" -Name "Rename" -Value 1

# Check if the directory exists, if not, create it
if (!(Test-Path -Path "C:\Windows\Client")) {
    New-Item -Path "C:\Windows\Client" -ItemType Directory -Force
}

# Create a text file
New-Item -Path "C:\Windows\Client\ClientRenameCompleted.txt" -ItemType File -Force

# Provide a 2 minute countdown timer to reboot the device
Show-RebootDialog -CountdownSeconds 120