#This script is used to install and configure bginfo for the current user.

#Requires -RunAsAdministrator

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

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

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