bin/optimize.ps1

# WinMole - System Optimization
# Clears caches, flushes DNS, refreshes services, cleans logs

param(
    [switch]$DryRun,
    [switch]$Debug
)

$ErrorActionPreference = 'SilentlyContinue'
. "$PSScriptRoot\..\lib\core.ps1"

$isAdmin = Test-IsAdmin

Write-Header -Title 'WinMole Optimize' -Sub $(if ($DryRun) { '(dry run)' } else { '' })

# ── System summary ────────────────────────────────────────────────────────────
$info = Get-SysInfoSummary
Write-SpectreHost " System: [grey]$($info.RamUsedGB)/$($info.RamTotalGB) GB RAM | $($info.DiskUsedGB)/$($info.DiskTotalGB) GB Disk | Uptime $($info.Uptime)[/]"
Write-Host ""

# ── Optimization task definition ──────────────────────────────────────────────
$tasks = @(
    [pscustomobject]@{
        Name          = 'Flush DNS cache'
        RequiresAdmin = $false
        Action        = { ipconfig /flushdns | Out-Null }
    }
    [pscustomobject]@{
        Name          = 'Clear thumbnail cache'
        RequiresAdmin = $false
        Action        = {
            $thumbDir = "$env:LOCALAPPDATA\Microsoft\Windows\Explorer"
            if (Test-Path $thumbDir) {
                Get-ChildItem -Path $thumbDir -Filter 'thumbcache_*.db' -ErrorAction SilentlyContinue |
                    Remove-Item -Force -ErrorAction SilentlyContinue
            }
        }
    }
    [pscustomobject]@{
        Name          = 'Clear icon cache'
        RequiresAdmin = $false
        Action        = {
            $iconCache = "$env:LOCALAPPDATA\IconCache.db"
            if (Test-Path $iconCache) {
                Remove-Item -LiteralPath $iconCache -Force -ErrorAction SilentlyContinue
            }
            $restartShell = $false
            if ($restartShell) {
                Stop-Process -Name explorer -Force -ErrorAction SilentlyContinue
                Start-Sleep -Milliseconds 500
                Start-Process explorer
            }
        }
    }
    [pscustomobject]@{
        Name          = 'Clear prefetch files'
        RequiresAdmin = $true
        Action        = {
            $pf = "$env:WINDIR\Prefetch"
            if (Test-Path $pf) {
                Get-ChildItem -Path $pf -ErrorAction SilentlyContinue |
                    Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
            }
        }
    }
    [pscustomobject]@{
        Name          = 'Clear Windows Update download cache'
        RequiresAdmin = $true
        Action        = {
            Stop-Service -Name wuauserv -Force -ErrorAction SilentlyContinue
            $wuDir = "$env:WINDIR\SoftwareDistribution\Download"
            if (Test-Path $wuDir) {
                Get-ChildItem -Path $wuDir -ErrorAction SilentlyContinue |
                    Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
            }
            Start-Service -Name wuauserv -ErrorAction SilentlyContinue
        }
    }
    [pscustomobject]@{
        Name          = 'Clean diagnostic and crash reports'
        RequiresAdmin = $false
        Action        = {
            $werPaths = @(
                "$env:LOCALAPPDATA\Microsoft\Windows\WER",
                "$env:APPDATA\Microsoft\Windows\WER",
                "$env:LOCALAPPDATA\CrashDumps"
            )
            foreach ($p in $werPaths) {
                if (Test-Path $p) {
                    Get-ChildItem -Path $p -Recurse -ErrorAction SilentlyContinue |
                        Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
                }
            }
        }
    }
    [pscustomobject]@{
        Name          = 'Clear Windows event logs'
        RequiresAdmin = $true
        Action        = {
            Get-WinEvent -ListLog * -ErrorAction SilentlyContinue |
                Where-Object { $_.IsEnabled -and $_.RecordCount -gt 0 } |
                ForEach-Object {
                    try { [System.Diagnostics.Eventing.Reader.EventLogSession]::GlobalSession.ClearLog($_.LogName) }
                    catch {}
                }
        }
    }
    [pscustomobject]@{
        Name          = 'Optimize startup programs (disable common bloat)'
        RequiresAdmin = $false
        Action        = {
            $startupKey = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
        }
    }
    [pscustomobject]@{
        Name          = 'Refresh Windows Search index'
        RequiresAdmin = $true
        Action        = {
            Restart-Service -Name WSearch -Force -ErrorAction SilentlyContinue
        }
    }
    [pscustomobject]@{
        Name          = 'Reset network adapter settings (renew DHCP)'
        RequiresAdmin = $true
        Action        = {
            ipconfig /release 2>&1 | Out-Null
            Start-Sleep -Seconds 1
            ipconfig /renew 2>&1 | Out-Null
        }
    }
    [pscustomobject]@{
        Name          = 'Run Disk Cleanup (cleanmgr) — silent'
        RequiresAdmin = $true
        Action        = {
            $sageset = 64
            $key = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
            Get-ChildItem $key -ErrorAction SilentlyContinue | ForEach-Object {
                Set-ItemProperty -Path $_.PSPath -Name "StateFlags$sageset" -Value 2 `
                    -Type DWord -ErrorAction SilentlyContinue
            }
            Start-Process -FilePath "$env:WINDIR\System32\cleanmgr.exe" `
                -ArgumentList "/sagerun:$sageset" -Wait -ErrorAction SilentlyContinue
        }
    }
)

# ── Execute tasks ─────────────────────────────────────────────────────────────
foreach ($task in $tasks) {
    $skip = $task.RequiresAdmin -and -not $isAdmin
    if ($skip) {
        Write-Warn "$($task.Name) — skipped (requires admin)"
        continue
    }

    if ($DryRun) {
        Write-Success -Message $task.Name -Right 'would run'
        continue
    }

    try {
        if ($Debug) { Write-Info "Running: $($task.Name)" }
        & $task.Action
        Write-Success -Message $task.Name
        Write-OpLog "Optimize: $($task.Name)"
    } catch {
        Write-Warn "$($task.Name) — error: $_"
    }
}

Write-Host ""
Write-Summary -Label 'System optimization completed' -Value ''

if (-not $isAdmin) {
    Write-SpectreHost " [yellow]Tip:[/] Re-run as Administrator to unlock all optimizations."
    Write-Host ""
}