# This script will install the components to make a Living Room PC
# Main focus is for gaming, primarily on Steam

# Requires running as administrator
#Requires -RunAsAdministrator

### Remove Bloatware
Write-Host "Starting debloating process..." -ForegroundColor Green

# Create Restore Point
Write-Host "Creating Restore Point..." -ForegroundColor Yellow
Enable-ComputerRestore -Drive "$env:SystemDrive"
Checkpoint-Computer -Description "Before Debloating" -RestorePointType "MODIFY_SETTINGS"

# Remove OneDrive
Write-Host "Removing OneDrive..." -ForegroundColor Yellow
taskkill /f /im OneDrive.exe
$onedrive = "$env:SYSTEMROOT\SysWOW64\OneDriveSetup.exe"
if (Test-Path $onedrive) {
    Start-Process $onedrive "/uninstall" -NoNewWindow -Wait
}
Remove-Item -Path "$env:USERPROFILE\OneDrive" -Force -Recurse -ErrorAction SilentlyContinue
Remove-Item -Path "$env:LOCALAPPDATA\Microsoft\OneDrive" -Force -Recurse -ErrorAction SilentlyContinue
Remove-Item -Path "$env:PROGRAMDATA\Microsoft OneDrive" -Force -Recurse -ErrorAction SilentlyContinue
Remove-Item -Path "$env:SYSTEMDRIVE\OneDriveTemp" -Force -Recurse -ErrorAction SilentlyContinue

# Install PowerShell 7 and set as default
Write-Host "Installing PowerShell 7..." -ForegroundColor Yellow
winget install -e --id Microsoft.PowerShell --accept-source-agreements --accept-package-agreements
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "DontUsePowerShellOnWinX" -Value 0 -Type DWord

# Debloat Edge
Write-Host "Debloating Edge..." -ForegroundColor Yellow
$edgePath = "$env:PROGRAMFILES(x86)\Microsoft\Edge\Application\msedge.exe"
if (Test-Path $edgePath) {
    Start-Process $edgePath "--uninstall --system-level --force-uninstall"
}

# Delete Temp Files
Write-Host "Cleaning temporary files..." -ForegroundColor Yellow
Remove-Item -Path "$env:TEMP\*" -Force -Recurse -ErrorAction SilentlyContinue
Remove-Item -Path "C:\Windows\Temp\*" -Force -Recurse -ErrorAction SilentlyContinue
Remove-Item -Path "C:\Windows\Prefetch\*" -Force -Recurse -ErrorAction SilentlyContinue

# Disable Various Features
Write-Host "Disabling unnecessary features..." -ForegroundColor Yellow
# Activity History
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\System" -Name "EnableActivityFeed" -Value 0
# Consumer Features
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\CloudContent" -Name "DisableWindowsConsumerFeatures" -Value 1
# Location Tracking
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location" -Name "Value" -Value "Deny"
# Storage Sense
Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy" -Name "01" -Value 0
# Telemetry
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection" -Name "AllowTelemetry" -Value 0
# WiFi Sense
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\WcmSvc\wifinetworkmanager\config" -Name "AutoConnectAllowedOEM" -Value 0

# Set Services to Manual
$servicesToManual = @(
    "DiagTrack"                                 # Connected User Experiences and Telemetry
    "dmwappushservice"                         # Device Management Wireless Application Protocol
    "HomeGroupListener"                        # HomeGroup Listener
    "HomeGroupProvider"                        # HomeGroup Provider
    "lfsvc"                                    # Geolocation Service
    "MapsBroker"                              # Downloaded Maps Manager
    "NetTcpPortSharing"                       # Net.Tcp Port Sharing Service
    "RemoteRegistry"                          # Remote Registry
    "SharedAccess"                            # Internet Connection Sharing
    "TrkWks"                                  # Distributed Link Tracking Client
    "WbioSrvc"                                # Windows Biometric Service
    "WMPNetworkSvc"                           # Windows Media Player Network Sharing Service
)

foreach ($service in $servicesToManual) {
    Write-Host "Setting $service to manual..." -ForegroundColor Yellow
    Set-Service -Name $service -StartupType Manual -ErrorAction SilentlyContinue
}

# Performance Optimizations
Write-Host "Applying performance optimizations..." -ForegroundColor Yellow
# Set visual effects for performance
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects" -Name "VisualFXSetting" -Value 2

# Run Disk Cleanup
Write-Host "Running Disk Cleanup..." -ForegroundColor Yellow
cleanmgr /sagerun:1

### Steam
# Install Steam using winget
Write-Host "Installing Steam..." -ForegroundColor Green
winget install -e --id Valve.Steam --accept-source-agreements --accept-package-agreements

### BGInfo
# Script variables
$bgInfoPath = "$env:USERPROFILE\.bginfo"

# Function to ensure a directory exists
function EnsureDirectory {
    param([string]$path)
    if (-not (Test-Path $path)) {
        New-Item -ItemType Directory -Path $path -Force | Out-Null
    }
}

# Install BGInfo using winget
Write-Host "Installing BGInfo..." -ForegroundColor Green
winget install -e --id Sysinternals.BGInfo --accept-source-agreements --accept-package-agreements

# Create .bginfo directory
Write-Host "Setting up BGInfo..." -ForegroundColor Green
EnsureDirectory $bgInfoPath

# Copy BGInfo scripts
Write-Host "Copying BGInfo scripts..." -ForegroundColor Yellow
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
Copy-Item "$scriptPath\bginfo\*" $bgInfoPath -Force

# Create scheduled task to run BGInfo at logon
$bgInfoExe = "$env:ProgramFiles\sysinternals\bginfo.exe"
$action = New-ScheduledTaskAction -Execute $bgInfoExe -Argument "$bgInfoPath\config.bgi /timer:0"
$trigger = New-ScheduledTaskTrigger -AtLogOn
$principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries

Write-Host "Creating BGInfo startup task..." -ForegroundColor Yellow
Register-ScheduledTask -TaskName "BGInfo" -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force

### Auto-Login Setup ###
Write-Host "Configuring Auto-Login..." -ForegroundColor Green

# Create registry path for auto-login
$RegPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
# Set auto-login registry values
Set-ItemProperty $RegPath "AutoAdminLogon" -Value "1" -Type String 
Set-ItemProperty $RegPath "DefaultUsername" -Value $env:USERNAME -Type String
# Note: In production you'd want to handle password more securely
# Set-ItemProperty $RegPath "DefaultPassword" -Value "YourPassword" -Type String

### Steam Big Picture Auto-Start ###
Write-Host "Setting up Steam Big Picture auto-start..." -ForegroundColor Green

$steamPath = "${env:ProgramFiles(x86)}\Steam\steam.exe"
$startupFolder = "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup"

# Create shortcut for Steam Big Picture
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$startupFolder\Steam.lnk")
$Shortcut.TargetPath = $steamPath
$Shortcut.Arguments = "-bigpicture"
$Shortcut.Save()

### HDMI-CEC Setup ###
Write-Host "Setting up HDMI-CEC control..." -ForegroundColor Green

# Create CEC scripts directory
$cecPath = "$env:USERPROFILE\.cec"
EnsureDirectory $cecPath

# Create TV power on script
@"
# CEC TV Power On
cec-client -s -d 1 "on 0"
"@ | Out-File -FilePath "$cecPath\tv-on.ps1" -Encoding ASCII

# Create TV power off script
@"
# CEC TV Power Off
cec-client -s -d 1 "standby 0"
"@ | Out-File -FilePath "$cecPath\tv-off.ps1" -Encoding ASCII

# Create scheduled tasks for TV control
$tvOnAction = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File `"$cecPath\tv-on.ps1`""
$tvOffAction = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File `"$cecPath\tv-off.ps1`""

# Trigger on wake from sleep for TV on
$tvOnTrigger = New-ScheduledTaskTrigger -AtStartup
$tvOffTrigger = New-ScheduledTaskTrigger -AtLogOff

Write-Host "Creating TV control tasks..." -ForegroundColor Yellow
Register-ScheduledTask -TaskName "TV Power On" -Action $tvOnAction -Trigger $tvOnTrigger -Principal $principal -Settings $settings -Force
Register-ScheduledTask -TaskName "TV Power Off" -Action $tvOffAction -Trigger $tvOffTrigger -Principal $principal -Settings $settings -Force

# Update TODO list with completed items
# TODO: Add remaining setup steps:
# - Performance optimizations
