<?php
// Отключаем вывод предупреждений, чтобы не портить бинарный вывод hex
error_reporting(0);

// Путь к клиенту World of Warcraft на сервере (относительно скрипта updater или абсолютный)
$base_client_dir = "../World of Warcraft"; 

function Get_All_Files($dir, &$results = array())
{
    if (!is_dir($dir)) return $results;

    $dh = new DirectoryIterator($dir);

    foreach ($dh as $item)
    {
        if (!$item->isDot())
        {
            if ($item->isDir())
            {
                Get_All_Files($item->getPathname(), $results);
            }
            else
            {
                $fileName = $item->getFilename();
                $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

                // Игнорируем служебные и системные файлы
                if ($extension !== "php" && $extension !== "htaccess" && $fileName !== "Thumbs.db")
                {
                    $filePath = $item->getPathname();
                    // Приводим все слэши к единому виду
                    $filePath = str_replace('\\', '/', $filePath);
                    
                    // Убираем префикс базовой директории, чтобы путь был относительным для клиента WoW
                    // Например: Data/patch-ruRU.MPQ
                    global $base_client_dir;
                    $cleanPath = ltrim(str_replace($base_client_dir, '', $filePath), '/');

                    $results[] = $cleanPath . "\r\n";
                }
            }
        }
    }
    return $results;
}

function Get_file_md5hash($file_path)
{
    global $base_client_dir;
    
    // Защита от выхода за пределы папки (LFI)
    $clean_relative = ltrim(str_replace(array('../', '..\\'), '', $file_path), '/');
    $full_path = $base_client_dir . '/' . $clean_relative;

    if (file_exists($full_path) && !is_dir($full_path))
    {
        return md5_file($full_path);
    }
    return "";
}

// 1. Обычные патчи и файлы игры
if (isset($_GET['patches']))
{
    $files = array();
    Get_All_Files($base_client_dir, $files);
    
    // Кодируем список в hex, как ожидает C# лаунчер
    echo "data=" . bin2hex(implode('', $files));
}
// 2. HD-патчи (если они лежат в отдельной папке, например ../World of Warcraft HD)
else if (isset($_GET['patches_hd']))
{
    $hd_dir = "../World of Warcraft HD";
    $files = array();
    Get_All_Files($hd_dir, $files);
    
    echo "data=" . bin2hex(implode('', $files));
}
// 3. Отдача контрольной суммы MD5 конкретного файла
else if (!empty($_GET['md5']))
{
    $file_path = $_GET['md5'];
    echo Get_file_md5hash($file_path);
}
?>