# Require Administrator privileges

$principal = New-Object Security.Principal.WindowsPrincipal(
    [Security.Principal.WindowsIdentity]::GetCurrent()
)

if (-not $principal.IsInRole(
    [Security.Principal.WindowsBuiltInRole]::Administrator
)) {

    Start-Process powershell `
        "-ExecutionPolicy Bypass -File `"$PSCommandPath`"" `
        -Verb RunAs `
        -WindowStyle Normal

    exit
}


Clear-Host

try {

    $raw = $host.UI.RawUI

    if ($raw.BufferSize.Width -lt 100) {

        $raw.BufferSize = New-Object System.Management.Automation.Host.Size(
            100,
            $raw.BufferSize.Height
        )

    }

    $raw.WindowSize = New-Object System.Management.Automation.Host.Size(
        100,
        35
    )

}
catch {
    # Ignore console sizing errors
}

try {

    $raw.ForegroundColor = "White"
    $raw.BackgroundColor = "Black"

    Clear-Host

}
catch {
}





Write-Host ""
Write-Host "==============================================" -ForegroundColor Cyan
Write-Host "        BACKGLASS SD CARD CLEANER"
Write-Host "==============================================" -ForegroundColor Cyan
Write-Host ""


# Find safe disks only

$disks = @(Get-Disk | Where-Object {

    $_.IsBoot -eq $false -and
    $_.IsSystem -eq $false -and
    $_.BusType -notin @(
        "RAID",
        "SATA",
        "ATA",
        "NVMe"
    ) -and
    $_.Size -gt 0

})


if ($disks.Count -eq 0) {

    Write-Host "No compatible SD cards found." -ForegroundColor Yellow
    Read-Host "Press Enter to close"
    exit

}


Write-Host "Available disks:"
Write-Host ""


$disks | Format-Table Number, FriendlyName, BusType, Size


foreach ($disk in $disks) {

    Write-Host ""
    Write-Host "Disk $($disk.Number) - $([math]::Round($disk.Size/1GB,1)) GB" -ForegroundColor Green
    Write-Host "    $($disk.FriendlyName)"


    $parts = Get-Partition -DiskNumber $disk.Number -ErrorAction SilentlyContinue


    if ($parts) {

        foreach ($p in $parts) {

            $label = ""

            try {

                $vol = Get-Volume -Partition $p -ErrorAction Stop


                if ($vol.FileSystemLabel) {

                    $label = $vol.FileSystemLabel

                }
                elseif ($vol.DriveLetter) {

                    $label = "$($vol.DriveLetter):"

                }
                else {

                    $label = "(No Label)"

                }

            }
            catch {

                $label = "(Unknown)"

            }


            Write-Host "      - $label"

        }

    }
    else {

        Write-Host "      - No partitions"

    }

}


Write-Host ""

$choice = Read-Host "Enter Disk Number to clear"


$disk = $disks | Where-Object {

    $_.Number -eq ($choice -as [int])

}


if ($null -eq $disk) {

    Write-Host "Invalid selection."
    Read-Host "Press Enter to close"

    exit

}


Write-Host ""

Write-Host "You selected:" -ForegroundColor Yellow
Write-Host "Disk $($disk.Number)"
Write-Host "$([math]::Round($disk.Size/1GB,1)) GB"
Write-Host "$($disk.FriendlyName)"
Write-Host ""


$confirm = Read-Host "Type CLEAR to erase this entire SD card"


if ($confirm -ne "CLEAR") {

    Write-Host "Cancelled."
    Read-Host "Press Enter to close"
    exit

}


$temp = Join-Path $env:TEMP "clearsd.txt"


@"
select disk $($disk.Number)
clean
create partition primary
format fs=exfat quick
assign
exit
"@ | Set-Content $temp -Encoding ASCII


Write-Host ""
Write-Host "Running DiskPart..."
Write-Host ""


diskpart /s $temp


Remove-Item $temp -Force


Write-Host ""

Write-Host "================================================" -ForegroundColor Green
Write-Host "          SD CARD CLEARED SUCCESSFULLY"
Write-Host "================================================" -ForegroundColor Green

Write-Host ""

Write-Host "The SD card has been reset and formatted." -ForegroundColor White

Write-Host ""

Write-Host "NEXT STEPS:" -ForegroundColor Yellow

Write-Host ""

Write-Host "  1. RETURN TO THE BACKGLASS SD CARD INSTALLER" -ForegroundColor Cyan

Write-Host ""

Write-Host "  2. CLICK  -->  REFRESH DEVICES" -ForegroundColor Yellow

Write-Host ""

Write-Host "  3. SELECT YOUR SD CARD" -ForegroundColor Cyan

Write-Host ""

Write-Host "  4. CLICK  -->  FLASH SD CARD" -ForegroundColor Yellow

Write-Host ""

Write-Host "================================================" -ForegroundColor Green

Write-Host ""

Read-Host "Press Enter to close"
