Install-PSResourceGet.ps1

# Manual PSResourceGet Installation - Direct Download Method
# Bypasses Install-Module to avoid "currently in use" lock errors

Write-Host "========================================================================" -ForegroundColor Cyan
Write-Host "Installing Microsoft.PowerShell.PSResourceGet (Direct Download Method)" -ForegroundColor Cyan
Write-Host "========================================================================" -ForegroundColor Cyan
Write-Host ""

# Setup paths
$tempPath = Join-Path $env:TEMP "PSResourceGetInstall"
$userModulePath = Join-Path ([Environment]::GetFolderPath("MyDocuments")) "WindowsPowerShell\Modules"
$nugetPath = Join-Path $tempPath "nuget.exe"

Write-Host "Temporary directory: $tempPath" -ForegroundColor Yellow
Write-Host "Installation path: $userModulePath" -ForegroundColor Yellow
Write-Host ""

# Create temp directory
if (Test-Path $tempPath) {
    Remove-Item $tempPath -Recurse -Force -ErrorAction SilentlyContinue
}
New-Item -ItemType Directory -Path $tempPath -Force | Out-Null

# Download NuGet.exe
Write-Host "Downloading NuGet.exe..." -ForegroundColor Green
try {
    $nugetUrl = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    Invoke-WebRequest -Uri $nugetUrl -OutFile $nugetPath -UseBasicParsing
    Write-Host "SUCCESS: NuGet.exe downloaded" -ForegroundColor Green
} catch {
    Write-Host "ERROR: Failed to download NuGet.exe - $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "Press any key to exit..."
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
}
Write-Host ""

# Download and install PSResourceGet
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Downloading Microsoft.PowerShell.PSResourceGet..." -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Cyan

$downloadPath = Join-Path $tempPath "PSResourceGet"
New-Item -ItemType Directory -Path $downloadPath -Force | Out-Null

Push-Location $downloadPath
try {
    # Download package
    Write-Host "Fetching latest version from PowerShell Gallery..." -ForegroundColor Green
    & $nugetPath install Microsoft.PowerShell.PSResourceGet -Source "https://www.powershellgallery.com/api/v2" -OutputDirectory . -NonInteractive -ExcludeVersion 2>&1 | Out-Null

    # Find the downloaded package folder
    $packageFolder = Get-ChildItem -Directory | Where-Object { $_.Name -eq "Microsoft.PowerShell.PSResourceGet" } | Select-Object -First 1

    if (-not $packageFolder) {
        throw "Package folder not found after download"
    }

    # Get version from the nuspec file
    $nuspecFile = Get-ChildItem -Path $packageFolder.FullName -Filter "*.nuspec" -Recurse | Select-Object -First 1
    if ($nuspecFile) {
        [xml]$nuspec = Get-Content $nuspecFile.FullName
        $version = $nuspec.package.metadata.version
        Write-Host "Downloaded version: $version" -ForegroundColor Green
    } else {
        # Fallback: try to detect version from folder structure
        $version = "1.0.0"
        Write-Host "Version detection: Using default $version" -ForegroundColor Yellow
    }

    # Setup destination
    $moduleDestination = Join-Path $userModulePath "Microsoft.PowerShell.PSResourceGet\$version"

    # Remove old version if exists
    $moduleBase = Join-Path $userModulePath "Microsoft.PowerShell.PSResourceGet"
    if (Test-Path $moduleBase) {
        Write-Host "Removing existing versions..." -ForegroundColor Yellow
        Remove-Item $moduleBase -Recurse -Force -ErrorAction SilentlyContinue
    }

    # Create destination
    New-Item -ItemType Directory -Path $moduleDestination -Force | Out-Null

    # Copy module files
    Write-Host "Installing to: $moduleDestination" -ForegroundColor Green
    Copy-Item -Path (Join-Path $packageFolder.FullName "*") -Destination $moduleDestination -Recurse -Force -Exclude "*.nuspec","*.nupkg"

    Write-Host ""
    Write-Host "SUCCESS: Microsoft.PowerShell.PSResourceGet $version installed!" -ForegroundColor Green

} catch {
    Write-Host ""
    Write-Host "ERROR: $($_.Exception.Message)" -ForegroundColor Red
    Pop-Location
    Write-Host "Press any key to exit..."
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
} finally {
    Pop-Location
}

# Cleanup temp files
Write-Host ""
Write-Host "Cleaning up..." -ForegroundColor Yellow
Remove-Item $tempPath -Recurse -Force -ErrorAction SilentlyContinue

# Configure PSResourceGet repository
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Configuring PSGallery repository..." -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Cyan

# Create PSResourceGet config directory
$psResourceGetPath = Join-Path $env:LOCALAPPDATA "PSResourceGet"
if (-not (Test-Path $psResourceGetPath)) {
    New-Item -ItemType Directory -Path $psResourceGetPath -Force | Out-Null
    Write-Host "Created config directory: $psResourceGetPath" -ForegroundColor Green
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Installation Complete!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Installed modules:" -ForegroundColor Yellow
Get-Module -Name Microsoft.PowerShell.PSResourceGet -ListAvailable |
    Select-Object Name, Version, Path |
    Format-Table -AutoSize
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "NEXT STEPS:" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "1. Close ALL PowerShell windows" -ForegroundColor White
Write-Host "2. Open a new PowerShell window" -ForegroundColor White
Write-Host "3. Run: Register-PSResourceRepository -PSGallery" -ForegroundColor White
Write-Host "4. Then use: Publish-PSResource -Path <module> -ApiKey <key>" -ForegroundColor White
Write-Host ""
Write-Host "Press any key to exit..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")