#!/usr/bin/env pwsh
<#
.SYNOPSIS
    Download WebDrop Bridge release installer from Forgejo via wget.

.DESCRIPTION
    Fetches the latest (or specified) WebDrop Bridge release from the Forgejo repository
    and downloads the appropriate installer (MSI for Windows, DMG for macOS) using wget.
    
    This script is useful for:
    - Enterprise deployments with proxy requirements
    - Automated deployment scripts
    - Initial setup before the built-in update mechanism kicks in
    - Admins preferring command-line tools for infrastructure automation

.PARAMETER Version
    Semantic version to download (e.g., "0.8.0"). 
    If not specified, downloads the latest release.
    Default: "latest"

.PARAMETER OutputDir
    Directory to save the downloaded installer.
    Default: Current directory

.PARAMETER Verify
    If $true, verify checksum against .sha256 file from release.
    Default: $true

.EXAMPLE
    # Download latest release to current directory
    .\download_release.ps1

.EXAMPLE
    # Download specific version to Downloads folder
    .\download_release.ps1 -Version "0.8.0" -OutputDir "$env:USERPROFILE\Downloads"

.EXAMPLE
    # Download without checksum verification
    .\download_release.ps1 -Verify $false

.NOTES
    Requires wget to be installed and available in PATH.
    Install via: choco install wget (Chocolatey) or winget install GNU.Wget
#>

param(
    [string]$Version = "latest",
    [string]$OutputDir = ".",
    [bool]$Verify = $true
)

# Configuration
$ForgejoUrl = "https://git.him-tools.de"
$Repo = "HIM-public/webdrop-bridge"
$ApiEndpoint = "$ForgejoUrl/api/v1/repos/$Repo/releases/$Version"

# Ensure output directory exists
if (-not (Test-Path $OutputDir)) {
    New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null
}

# Resolve to absolute path
$OutputDirAbs = (Resolve-Path $OutputDir).Path

Write-Host "🚀 WebDrop Bridge Download Script" -ForegroundColor Cyan
Write-Host "Version: $Version"
Write-Host "Output: $OutputDirAbs"
Write-Host ""

# Check if wget is installed
try {
    $wgetVersion = (wget --version 2>&1 | Select-Object -First 1)
    Write-Host "✓ wget found: $wgetVersion" -ForegroundColor Green
} catch {
    Write-Host "❌ wget not found. Install via:" -ForegroundColor Red
    Write-Host "   choco install wget" -ForegroundColor Yellow
    Write-Host "   or" -ForegroundColor Yellow
    Write-Host "   winget install GNU.Wget" -ForegroundColor Yellow
    exit 1
}

# Fetch release info from Forgejo API
Write-Host "📥 Fetching release information from Forgejo..." -ForegroundColor Cyan
try {
    $response = Invoke-WebRequest -Uri $ApiEndpoint -UseBasicParsing -ErrorAction Stop
    $releaseData = ConvertFrom-Json $response.Content
} catch {
    Write-Host "❌ Failed to fetch release info: $_" -ForegroundColor Red
    exit 1
}

if (-not $releaseData) {
    Write-Host "❌ Release not found: $Version" -ForegroundColor Red
    exit 1
}

$TagName = $releaseData.tag_name
$ReleaseName = $releaseData.name
Write-Host "📦 Found release: $ReleaseName ($TagName)" -ForegroundColor Green

# Find installer asset (.msi for Windows, .dmg for macOS)
$InstallerAsset = $null
$Sha256Asset = $null

foreach ($asset in $releaseData.assets) {
    $assetName = $asset.name
    if ($assetName -match '\.(msi|dmg)$') {
        $InstallerAsset = $asset
    }
    if ($assetName -match '\.sha256$') {
        $Sha256Asset = $asset
    }
}

if (-not $InstallerAsset) {
    Write-Host "❌ No installer found in release (looking for .msi or .dmg)" -ForegroundColor Red
    exit 1
}

$InstallerName = $InstallerAsset.name
$InstallerUrl = $InstallerAsset.browser_download_url
$InstallerPath = Join-Path $OutputDirAbs $InstallerName

Write-Host "💾 Downloading: $InstallerName" -ForegroundColor Cyan
Write-Host "   URL: $InstallerUrl" -ForegroundColor Gray

# Download using wget
try {
    & wget -O $InstallerPath $InstallerUrl -q --show-progress
    if ($LASTEXITCODE -ne 0) {
        throw "wget exited with code $LASTEXITCODE"
    }
} catch {
    Write-Host "❌ Download failed: $_" -ForegroundColor Red
    if (Test-Path $InstallerPath) {
        Remove-Item $InstallerPath -Force
    }
    exit 1
}

Write-Host "✓ Downloaded: $InstallerPath" -ForegroundColor Green

# Verify checksum if requested
if ($Verify -and $Sha256Asset) {
    Write-Host ""
    Write-Host "🔍 Verifying checksum..." -ForegroundColor Cyan
    
    $Sha256Url = $Sha256Asset.browser_download_url
    $Sha256Path = Join-Path $OutputDirAbs "$InstallerName.sha256"
    
    try {
        & wget -O $Sha256Path $Sha256Url -q
        if ($LASTEXITCODE -ne 0) {
            throw "Failed to download checksum"
        }
        
        # Read checksum file (format: "hash  filename")
        $checksumContent = Get-Content $Sha256Path
        $expectedHash = ($checksumContent -split '\s+')[0]
        
        # Calculate SHA256 of downloaded file
        $actualHash = (Get-FileHash -Path $InstallerPath -Algorithm SHA256).Hash.ToLower()
        
        if ($actualHash -eq $expectedHash.ToLower()) {
            Write-Host "✓ Checksum verified" -ForegroundColor Green
        } else {
            Write-Host "❌ Checksum mismatch!" -ForegroundColor Red
            Write-Host "   Expected: $expectedHash" -ForegroundColor Yellow
            Write-Host "   Actual:   $actualHash" -ForegroundColor Yellow
            Remove-Item $InstallerPath -Force
            Remove-Item $Sha256Path -Force
            exit 1
        }
        
        # Clean up checksum file
        Remove-Item $Sha256Path -Force
    } catch {
        Write-Host "⚠ Checksum verification failed: $_" -ForegroundColor Yellow
        Write-Host "   Installer downloaded but not verified" -ForegroundColor Yellow
    }
} elseif ($Verify -and -not $Sha256Asset) {
    Write-Host "⚠ No checksum file in release, skipping verification" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "✅ Download complete!" -ForegroundColor Green
Write-Host ""
Write-Host "Next steps:" -ForegroundColor Cyan
Write-Host "  1. Review: $InstallerPath"
Write-Host "  2. Execute installer to install WebDrop Bridge"
Write-Host "  3. Launch application and configure paths/URLs in settings"
Write-Host ""
