# install.ps1 — kopírovanie súborov prekladu
# Volané z INSTALUJ.bat. Používa \\?\ prefix, takže zvládne aj cesty nad 260 znakov.
param(
    [Parameter(Mandatory=$true)][string]$Src,
    [Parameter(Mandatory=$true)][string]$Game,
    [Parameter(Mandatory=$true)][string]$Bundle
)

$ErrorActionPreference = 'Stop'

function LongPath([string]$p) {
    if ($p.StartsWith('\\?\')) { return $p }
    return '\\?\' + $p
}

function Get-Md5([byte[]]$bytes) {
    $md5 = [Security.Cryptography.MD5]::Create()
    return ([BitConverter]::ToString($md5.ComputeHash($bytes))) -replace '-', ''
}

# Vydání hry se liší souborem sharedassets0.assets. Rozlišujeme podle jeho
# velikosti — originální i už počeštěná varianta, aby šla instalace zopakovat.
$variants = @(
    @{
        Name     = 'Steam (build 24809473)'
        OrigSize = 11448624
        DoneSize = 12422936
        Font     = 'font_steam.assets'
        Atlas    = $null          # atlas je uvnitř .assets
    },
    @{
        Name     = 'standalone v1.2'
        OrigSize = 11586000
        DoneSize = 11510888
        Font     = 'font_v12.assets'
        Atlas    = @{             # atlas je streamovaný v .resS
            File       = 'atlas_v12.bin'
            Target     = 'sharedassets0.assets.resS'
            Offset     = 175576192
            Length     = 1048576
            OrigMd5    = 'AEE9C9D3A6CED8025A197BDB4B7F9AE2'
            PatchedMd5 = '3D5B8289CF399F1812CA3CA5F29DAB52'
        }
    }
)

$data = Join-Path $Game 'Everything is Crab_Data'
$aa   = Join-Path $data 'StreamingAssets\aa'
$sw   = Join-Path $aa   'StandaloneWindows64'

try {
    # ---------- Preklad textov ----------
    $jobs = @(
        @{ From = Join-Path $Src 'catalog.bin';   To = Join-Path $aa 'catalog.bin' }
        @{ From = Join-Path $Src 'polish.bundle'; To = Join-Path $sw $Bundle }
    )

    foreach ($j in $jobs) {
        $from = LongPath $j.From
        $to   = LongPath $j.To
        $bak  = $to + '.orig_backup'

        if (-not (Test-Path -LiteralPath $from)) { throw "Chybi zdrojovy soubor: $($j.From)" }
        if ((Test-Path -LiteralPath $to) -and -not (Test-Path -LiteralPath $bak)) {
            Copy-Item -LiteralPath $to -Destination $bak -Force
        }
        Copy-Item -LiteralPath $from -Destination $to -Force
        Write-Host ('  OK  ' + (Split-Path $j.To -Leaf))
    }

    # ---------- Font (podle vydání hry) ----------
    $fontPath = LongPath (Join-Path $data 'sharedassets0.assets')
    if (-not (Test-Path -LiteralPath $fontPath)) { throw 'Chybi sharedassets0.assets ve hre' }
    $fontSize = (Get-Item -LiteralPath $fontPath).Length

    $v = $variants | Where-Object { $_.OrigSize -eq $fontSize -or $_.DoneSize -eq $fontSize } | Select-Object -First 1

    if (-not $v) {
        Write-Host ''
        Write-Host '  PRESKOCENO  sharedassets0.assets - nezname vydani hry'
        Write-Host ("              (velikost {0} B)" -f $fontSize)
        Write-Host '              Text bude cesky, diakritika se nemusi zobrazit.'
        exit 0
    }

    Write-Host ''
    Write-Host ('  Vydani hry: ' + $v.Name)

    # Atlas v .resS musí sedět, jinak font nenasazujeme
    if ($v.Atlas) {
        $ress = LongPath (Join-Path $data $v.Atlas.Target)
        if (-not (Test-Path -LiteralPath $ress)) { throw "Chybi $($v.Atlas.Target)" }

        $fs = [IO.File]::OpenRead($ress)
        try {
            $buf = New-Object byte[] $v.Atlas.Length
            [void]$fs.Seek($v.Atlas.Offset, 'Begin')
            [void]$fs.Read($buf, 0, $v.Atlas.Length)
        } finally { $fs.Close() }

        $cur = Get-Md5 $buf
        if ($cur -ne $v.Atlas.OrigMd5 -and $cur -ne $v.Atlas.PatchedMd5) {
            Write-Host ''
            Write-Host '  PRESKOCENO  font - soubor .resS neodpovida ocekavane verzi.'
            Write-Host '              Text bude cesky, diakritika se nemusi zobrazit.'
            exit 0
        }

        # záloha .resS regionu (jen originál, jednou)
        $ressBak = $ress + '.atlas_backup'
        if ($cur -eq $v.Atlas.OrigMd5 -and -not (Test-Path -LiteralPath $ressBak)) {
            [IO.File]::WriteAllBytes($ressBak, $buf)
        }

        $atlas = LongPath (Join-Path $Src $v.Atlas.File)
        if (-not (Test-Path -LiteralPath $atlas)) { throw "Chybi $($v.Atlas.File)" }
        $newBytes = [IO.File]::ReadAllBytes($atlas)
        if ($newBytes.Length -ne $v.Atlas.Length) { throw 'Nespravna velikost atlasu' }

        $fs = [IO.File]::Open($ress, 'Open', 'ReadWrite')
        try {
            [void]$fs.Seek($v.Atlas.Offset, 'Begin')
            $fs.Write($newBytes, 0, $newBytes.Length)
        } finally { $fs.Close() }
        Write-Host ('  OK  ' + $v.Atlas.Target + ' (atlas fontu)')
    }

    $fontSrc = LongPath (Join-Path $Src $v.Font)
    if (-not (Test-Path -LiteralPath $fontSrc)) { throw "Chybi $($v.Font)" }
    $fontBak = $fontPath + '.orig_backup'
    if ($fontSize -eq $v.OrigSize -and -not (Test-Path -LiteralPath $fontBak)) {
        Copy-Item -LiteralPath $fontPath -Destination $fontBak -Force
    }
    Copy-Item -LiteralPath $fontSrc -Destination $fontPath -Force
    Write-Host '  OK  sharedassets0.assets (cesky font)'

    exit 0
}
catch {
    Write-Host ''
    Write-Host ('  CHYBA: ' + $_.Exception.Message)
    exit 1
}
