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

# Apps to be installed:
# - Steam (winget: Valve.Steam, choco: steam)
# - PowerShell 7 (winget: Microsoft.PowerShell, choco: powershell-core)
# - BGInfo (winget: Sysinternals.BGInfo, choco: bginfo)
# - VCRedist (winget: Microsoft.VCRedist.2015+.x64, choco: vcredist140)
# - btop4win (winget: not available, choco: btop4win)
# - Microsoft Edit (winget: Microsoft.Edit, choco: not available)

# Requires running as administrator
#Requires -RunAsAdministrator

### Package Manager Setup ###
Write-Host "Setting up package managers..." -ForegroundColor Green

# Check and setup Winget
Write-Host "Checking Winget..." -ForegroundColor Yellow
$wingetPath = Get-Command winget -ErrorAction SilentlyContinue

if (-not $wingetPath) {
    Write-Host "Winget is not installed. Installing via Microsoft Store..." -ForegroundColor Yellow
    Start-Process "ms-windows-store://pdp/?ProductId=9NBLGGH4NNS1"
    exit 1
}

# Check Winget version
$wingetVersion = (winget --version)
Write-Host "Current Winget version: $wingetVersion" -ForegroundColor Green

# Update Winget
Write-Host "Updating Winget..." -ForegroundColor Yellow
winget upgrade --all --include-unknown

# Setup Chocolatey
Write-Host "Setting up Chocolatey..." -ForegroundColor Yellow

# Set TLS 1.2 for security
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072

# Check if Chocolatey is already installed
if (-not (Get-Command choco -ErrorAction SilentlyContinue)) {
    Write-Host "Installing Chocolatey..." -ForegroundColor Yellow
    
    # Create the installation directory if it doesn't exist
    $chocoPath = "$env:ProgramData\chocolatey"
    if (-not (Test-Path $chocoPath)) {
        New-Item -ItemType Directory -Path $chocoPath -Force | Out-Null
    }

    # Download and run the Chocolatey installation script
    $installScript = "https://community.chocolatey.org/install.ps1"
    $tempFile = [System.IO.Path]::GetTempFileName()
    
    try {
        Invoke-WebRequest -Uri $installScript -OutFile $tempFile
        & $tempFile
    }
    catch {
        Write-Error "Failed to install Chocolatey: $_"
        exit 1
    }
    finally {
        if (Test-Path $tempFile) {
            Remove-Item $tempFile -Force
        }
    }
}
else {
    Write-Host "Chocolatey is already installed." -ForegroundColor Green
}

# Verify Chocolatey installation
$chocoVersion = (choco --version)
Write-Host "Chocolatey version: $chocoVersion" -ForegroundColor Green

# Update Chocolatey
Write-Host "Updating Chocolatey..." -ForegroundColor Yellow
choco upgrade chocolatey -y

### Function to Install Apps ###
function Install-App {
    param (
        [string]$AppName,
        [string]$WingetId,
        [string]$ChocoId,
        [switch]$UseChocoOnly
    )

    Write-Host "Installing $AppName..." -ForegroundColor Yellow
    
    if ($UseChocoOnly) {
        Write-Host "Using Chocolatey for $AppName..." -ForegroundColor Yellow
        choco install $ChocoId -y
        return
    }

    try {
        Write-Host "Attempting to install $AppName via Winget..." -ForegroundColor Yellow
        winget install -e --id $WingetId --accept-source-agreements --accept-package-agreements
    }
    catch {
        Write-Host "Winget installation failed, falling back to Chocolatey..." -ForegroundColor Yellow
        choco install $ChocoId -y
    }
}

### 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
Install-App -AppName "PowerShell 7" -WingetId "Microsoft.PowerShell" -ChocoId "powershell-core"
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
Install-App -AppName "Steam" -WingetId "Valve.Steam" -ChocoId "steam"

### Install Required Components
Write-Host "Installing required components..." -ForegroundColor Green

# Install VCRedist
Install-App -AppName "Visual C++ Redistributable" -WingetId "Microsoft.VCRedist.2015+.x64" -ChocoId "vcredist140"

# Install OpenSSH using PowerShell method
Write-Host "Installing OpenSSH..." -ForegroundColor Yellow

# Check if OpenSSH is available
$sshCapabilities = Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'
Write-Host "Available OpenSSH capabilities:" -ForegroundColor Yellow
$sshCapabilities | Format-Table Name, State

# Install OpenSSH Client and Server
Write-Host "Installing OpenSSH components..." -ForegroundColor Yellow
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

# Start and configure OpenSSH Server
Write-Host "Configuring OpenSSH Server..." -ForegroundColor Yellow
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'

# Configure Windows Firewall for SSH
Write-Host "Configuring Windows Firewall for SSH..." -ForegroundColor Yellow
if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) {
    Write-Host "Creating firewall rule for SSH..." -ForegroundColor Yellow
    New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
} else {
    Write-Host "Firewall rule for SSH already exists." -ForegroundColor Green
}

# Install btop4win (Chocolatey only)
# Note: btop4win requires Visual C++ Redistributable 2015-2022 (x86) to be installed first
Write-Host "Installing Visual C++ Redistributable 2015-2022 (x86)..." -ForegroundColor Yellow
Install-App -AppName "Visual C++ Redistributable 2015-2022 (x86)" -WingetId "Microsoft.VCRedist.2015+.x86" -ChocoId "vcredist140"

Write-Host "Installing btop4win..." -ForegroundColor Yellow
Install-App -AppName "btop4win" -ChocoId "btop4win" -UseChocoOnly

# Install Microsoft Edit
Install-App -AppName "Microsoft Edit" -WingetId "Microsoft.Edit" -ChocoId ""

### Function to Setup BGInfo ###
function Setup-BGInfo {
    param (
        [string]$ConfigPath = "$env:USERPROFILE\.bginfo\config.bgi"
    )

    Write-Host "Setting up BGInfo..." -ForegroundColor Yellow

    # Create BGInfo directory
    $bginfoPath = "$env:USERPROFILE\.bginfo"
    if (-not (Test-Path $bginfoPath)) {
        New-Item -ItemType Directory -Path $bginfoPath -Force | Out-Null
    }

    # Install BGInfo using winget
    Install-App -AppName "BGInfo" -WingetId "Sysinternals.BGInfo" -ChocoId "bginfo"

    # 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 "$ConfigPath /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

    # Run BGInfo immediately
    Write-Host "Running BGInfo..." -ForegroundColor Yellow
    Start-Process $bgInfoExe -ArgumentList "$ConfigPath /timer:0" -NoNewWindow -Wait
}

### BGInfo Setup ###
Write-Host "Setting up BGInfo..." -ForegroundColor Green
Setup-BGInfo

### 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
