# kuberoku installer for Windows
#
# Usage:
#   irm https://github.com/amanjain/kuberoku/releases/latest/download/install.ps1 | iex
#
# Environment variables:
#   KUBEROKU_VERSION      — install a specific version (e.g. "v0.1.0"), default: latest
#   KUBEROKU_INSTALL_DIR  — custom install directory, default: ~\.kuberoku\bin

$ErrorActionPreference = "Stop"

$Repo = "amanjain/kuberoku"
$BinaryName = "kuberoku.exe"

# --- resolve version ---

if ($env:KUBEROKU_VERSION) {
    $Version = $env:KUBEROKU_VERSION
} else {
    $Release = Invoke-RestMethod -Uri "https://api.github.com/repos/$Repo/releases/latest"
    $Version = $Release.tag_name
    if (-not $Version) {
        Write-Error "Could not determine latest version. Set KUBEROKU_VERSION."
        exit 1
    }
}

# --- resolve install dir ---

if ($env:KUBEROKU_INSTALL_DIR) {
    $InstallDir = $env:KUBEROKU_INSTALL_DIR
} else {
    $InstallDir = Join-Path $env:USERPROFILE ".kuberoku\bin"
}

New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null

# --- download ---

$Asset = "kuberoku-windows-amd64.exe"
$Url = "https://github.com/$Repo/releases/download/$Version/$Asset"
$Dest = Join-Path $InstallDir $BinaryName

Write-Host "[kuberoku] version:  $Version"
Write-Host "[kuberoku] target:   $Dest"
Write-Host "[kuberoku] downloading $Url ..."

Invoke-WebRequest -Uri $Url -OutFile $Dest -UseBasicParsing

if (-not (Test-Path $Dest) -or (Get-Item $Dest).Length -eq 0) {
    Write-Error "Download failed — file is empty."
    exit 1
}

# --- verify ---

try {
    $VersionOutput = & $Dest --version 2>&1
    Write-Host "[kuberoku] installed: $VersionOutput"
} catch {
    Write-Host "[kuberoku] installed to $Dest (could not verify version)"
}

# --- add to PATH ---

$UserPath = [Environment]::GetEnvironmentVariable("Path", "User")
if ($UserPath -notlike "*$InstallDir*") {
    [Environment]::SetEnvironmentVariable("Path", "$UserPath;$InstallDir", "User")
    Write-Host "[kuberoku] added $InstallDir to your PATH (restart your terminal to use it)"
}

Write-Host "[kuberoku] done! Run 'kuberoku --help' to get started."
