$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Definition
$logFile = "$scriptDirectory\registry_deletion_log.txt"

# Ensure the script is running with administrative privileges
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltinRole] "Administrator")) {
    Write-Output "Script requires administrative privileges. Please run PowerShell as Administrator."
    Exit
}

# Function to write to the log using UTF8 encoding
function Write-Log {
    param (
        [string]$Message
    )
    # Ensure the log file exists
    if (-not (Test-Path -Path $logFile)) {
        [System.IO.File]::WriteAllText($logFile, "")
    }
    # Append the message with a newline
    [System.IO.File]::AppendAllText($logFile, "$Message`n", [System.Text.Encoding]::UTF8)
}

# Function to read the log content
function Read-Log {
    if (Test-Path -Path $logFile) {
        return [System.IO.File]::ReadAllText($logFile)
    }
    else {
        return ""
    }
}

# Create or clear the log file
if (Test-Path -Path $logFile) {
    Remove-Item -Path $logFile -Force
}

# Create a new log file
New-Item -Path $logFile -ItemType File -Force | Out-Null

# Initialize the log
Write-Log "Registry Deletion Log - $(Get-Date)"
Write-Log "===========================================`n"

# Initialize counters
$deletedCount = 0
$notFoundCount = 0
$failedDeletionCount = 0

# Function to remove registry keys that contain specific text
function Remove-RegistryKeyContainingText {
    param (
        [string]$Path,
        [string]$Text
    )
    if (Test-Path -Path "Registry::$Path") {
        try {
            $keys = Get-ChildItem -Path "Registry::$Path" | Where-Object { $_.PSChildName -imatch $Text }
            if ($keys.Count -eq 0) {
                Write-Log "No keys found containing '$Text' in $Path"
            }
            foreach ($key in $keys) {
                try {
                    $keyContents = Get-ItemProperty -Path $key.PSPath | Out-String
                    Write-Log "Contents of $($key.PSPath): `n$keyContents"
                } catch {
                    Write-Log "Unable to retrieve contents of $($key.PSPath): $($_.Exception.Message)"
                }
                Remove-Item -Path "$($key.PSPath)" -Force -Recurse
                Write-Log "Deleted: $($key.PSPath)"
                $deletedCount++
            }
        } catch {
            Write-Log "Failed to delete keys in: $Path - $($_.Exception.Message)"
            $failedDeletionCount++
        }
    } else {
        Write-Log "Not Found: $Path"
        $notFoundCount++
    }
}

# Registry paths to be searched
$registryPaths = @(
    "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FeatureUsage\AppLaunch",
    "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FeatureUsage\AppSwitched",
    "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FeatureUsage\ShowJumpView"
)

# Process each registry path to find and remove keys containing 'Private Keeper'
foreach ($path in $registryPaths) {
    Remove-RegistryKeyContainingText -Path $path -Text "Private Keeper|PrivateKeeper"
}

# Remove the entire 'Private Keeper' key from HKEY_CURRENT_USER\SOFTWARE
$privateKeeperPath = "HKEY_CURRENT_USER\SOFTWARE\Private Keeper"
if (Test-Path -Path "Registry::$privateKeeperPath") {
    try {
        try {
            $keyContents = Get-ItemProperty -Path "Registry::$privateKeeperPath" | Out-String
            Write-Log "Contents of ${privateKeeperPath}: `n$keyContents"
        } catch {
            Write-Log "Unable to retrieve contents of ${privateKeeperPath}: $($_.Exception.Message)"
        }
        Remove-Item -Path "Registry::$privateKeeperPath" -Force -Recurse
        Write-Log "Deleted: $privateKeeperPath"
        $deletedCount++
    } catch {
        Write-Log "Failed to delete: $privateKeeperPath - $($_.Exception.Message)"
        $failedDeletionCount++
    }
} else {
    Write-Log "Not Found: $privateKeeperPath"
}

# Finalize the log
Write-Log "===========================================`n"
Write-Log "Script execution completed on: $(Get-Date)"
Write-Log "Total deleted keys: $deletedCount"
Write-Log "Total not found keys: $notFoundCount"
Write-Log "Total failed deletions: $failedDeletionCount"

Write-Output "Registry Deletion Script Completed. Please check the log file at $logFile for details."

# Display log contents in the console
$logContents = Read-Log
Write-Output $logContents

# Wait for user input to close
Write-Output "Press Enter to exit..."
[System.Console]::ReadLine()
