# find_game.ps1 — najde slozku hry Everything is Crab.
# Vypise jednu radku s cestou, nebo nic. Volane z INSTALUJ.bat.
$ErrorActionPreference = 'SilentlyContinue'

$EXE = 'Everything is Crab.exe'

function Test-Game([string]$dir) {
    if (-not $dir) { return $false }
    return Test-Path -LiteralPath (Join-Path $dir $EXE)
}

$found = New-Object System.Collections.Generic.List[string]

# --- 1) Steam knihovny ---
$steamRoots = New-Object System.Collections.Generic.List[string]

foreach ($k in 'HKCU:\Software\Valve\Steam', 'HKLM:\SOFTWARE\WOW6432Node\Valve\Steam', 'HKLM:\SOFTWARE\Valve\Steam') {
    foreach ($prop in 'SteamPath', 'InstallPath') {
        $p = (Get-ItemProperty -Path $k -Name $prop).$prop
        if ($p) { $steamRoots.Add(($p -replace '/', '\').TrimEnd('\')) }
    }
}
foreach ($p in "${env:ProgramFiles(x86)}\Steam", "$env:ProgramFiles\Steam") {
    if ($p) { $steamRoots.Add($p) }
}

$libs = New-Object System.Collections.Generic.List[string]
foreach ($root in ($steamRoots | Select-Object -Unique)) {
    if (-not (Test-Path -LiteralPath $root)) { continue }
    $libs.Add($root)

    # libraryfolders.vdf — knihovny na dalsich discich
    foreach ($vdf in "$root\steamapps\libraryfolders.vdf", "$root\config\libraryfolders.vdf") {
        if (-not (Test-Path -LiteralPath $vdf)) { continue }
        $txt = Get-Content -LiteralPath $vdf -Raw
        # novy format:  "path"  "D:\\SteamLibrary"
        # stary format: "1"     "D:\\SteamLibrary"
        foreach ($m in [regex]::Matches($txt, '"(?:path|\d+)"\s*"([^"]+)"')) {
            $lib = $m.Groups[1].Value -replace '\\\\', '\'
            if ($lib -match '^[A-Za-z]:') { $libs.Add($lib.TrimEnd('\')) }
        }
    }
}

foreach ($lib in ($libs | Select-Object -Unique)) {
    $g = Join-Path $lib 'steamapps\common\Everything is Crab'
    if (Test-Game $g) { $found.Add($g) }
}

# --- 2) Epic Games ---
foreach ($mf in (Get-ChildItem "$env:ProgramData\Epic\EpicGamesLauncher\Data\Manifests\*.item" -File)) {
    $j = Get-Content -LiteralPath $mf.FullName -Raw | ConvertFrom-Json
    if ($j.InstallLocation -and (Test-Game $j.InstallLocation)) { $found.Add($j.InstallLocation) }
}

# --- 3) GOG ---
foreach ($k in (Get-ChildItem 'HKLM:\SOFTWARE\WOW6432Node\GOG.com\Games', 'HKLM:\SOFTWARE\GOG.com\Games')) {
    $p = (Get-ItemProperty -Path $k.PSPath -Name 'path').path
    if (Test-Game $p) { $found.Add($p) }
}

# --- 4) Bezne slozky na vsech discich (posledni moznost) ---
if ($found.Count -eq 0) {
    $drives = Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Free -ne $null }
    foreach ($d in $drives) {
        foreach ($sub in 'SteamLibrary\steamapps\common', 'Games', 'Hry', 'Steam\steamapps\common') {
            $g = Join-Path $d.Root (Join-Path $sub 'Everything is Crab')
            if (Test-Game $g) { $found.Add($g) }
        }
    }
}

$hit = $found | Select-Object -Unique | Select-Object -First 1
if ($hit) { Write-Output $hit }
