<?php
declare(strict_types=1);

if ($argc < 4) {
    fwrite(STDERR, "Uso: php patch_native_url.php OmniMax.apk https://seu-dominio/api4/ OmniMax-patched.apk\n");
    exit(1);
}

$input = $argv[1];
$newUrl = rtrim($argv[2], '/') . '/';
$output = $argv[3];
$old = 'https://api01.ottrun.com/api4/';

if (!is_file($input)) {
    fwrite(STDERR, "APK de entrada nao encontrado.\n");
    exit(1);
}

if (strlen($newUrl) > strlen($old)) {
    fwrite(STDERR, "A nova URL tem " . strlen($newUrl) . " caracteres. Para patch binario direto, use no maximo " . strlen($old) . ".\n");
    exit(1);
}

copy($input, $output);
$zip = new ZipArchive();
if ($zip->open($output) !== true) {
    fwrite(STDERR, "Nao foi possivel abrir o APK de saida.\n");
    exit(1);
}

$replacement = $newUrl . str_repeat("\0", strlen($old) - strlen($newUrl));
$patched = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
    $name = $zip->getNameIndex($i);
    if (!preg_match('#^lib/.+/libnative-lib\.so$#', $name)) {
        continue;
    }
    $data = $zip->getFromIndex($i);
    if ($data === false || strpos($data, $old) === false) {
        continue;
    }
    $data = str_replace($old, $replacement, $data);
    $zip->deleteName($name);
    $zip->addFromString($name, $data);
    $patched++;
}
$zip->close();

echo "Bibliotecas nativas alteradas: {$patched}\n";
echo "APK gerado: {$output}\n";
echo "Assine o APK novamente antes de instalar.\n";
