$ErrorActionPreference = 'Stop'

$repo = Join-Path $env:USERPROFILE 'TibiaPilotNG'
$secretPath = Join-Path $repo '.login-secret'

try {
    $encoded = [Console]::In.ReadToEnd().Trim()
    $password = [Text.Encoding]::UTF8.GetString(
        [Convert]::FromBase64String($encoded)
    )
    $utf8 = [Text.UTF8Encoding]::new($false)
    [IO.File]::WriteAllText($secretPath, $password, $utf8)
    icacls.exe $secretPath /inheritance:r /grant:r "$env:USERNAME`:(F)" 'SYSTEM:(F)' | Out-Null
    & (Join-Path $repo 'tools\Run-Login-Tibia.ps1')
    exit $LASTEXITCODE
}
finally {
    Remove-Item $secretPath -Force -ErrorAction SilentlyContinue
}
