<?php
/**
 * update.php - manifest MD5 cho host cap nhat MOBILE (update.pgame.vn).
 *
 * Client mobile/Mac (KUpdateLayer, 260930) va tool JXPakDev tai:  http://update.pgame.vn/update.php
 * Tra ve (CUNG dinh dang update.php cua host PC updatehk):
 *     <AutoUpdate>
 *       <Folder Name="data" />
 *       <File   Name="data/hkmb1.pak" MD5="..." />
 *     </AutoUpdate>
 * Name tinh tu thu muc chua update.php (web root) -> client tai http://update.pgame.vn/<Name>.
 * Chi quet cac thu muc trong $DIRS (mac dinh 'data').
 *
 * KHAC ban PC: so MD5 luu theo TUNG TEP (co + mtime + inode). Dat pak moi / thay pak -> lan goi ke tiep CHI bam
 * tep do (pak 200 MB ~1 s), khong bam lai ca cay. Khoa flock khi bam: dong nguoi goi cung luc chi mot tien trinh
 * bam, tien trinh khac doi roi doc so. Bo qua tep dang tai len (.filepart cua WinSCP, .part, .tmp, .uploading) va
 * tep an -> tai pak len bang WinSCP (mac dinh ghi .filepart roi doi ten) thi manifest khong bao gio co pak do dang.
 *
 * Trien khai: dat tep nay CANH thu muc data/ (web root); nginx chuyen dung /update.php sang php-fpm, KHONG cache;
 * chan /.manifest_cache.json (tep an). Ham so lan dau bang chinh user cua php-fpm:
 *     sudo -u www-data php update.php > /dev/null
 */

header('Content-Type: text/xml; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
@set_time_limit(900);

$BASE  = __DIR__;
$DIRS  = array('data');
$CACHE = __DIR__ . DIRECTORY_SEPARATOR . '.manifest_cache.json';
$SKIP  = '/(^\.|\.filepart$|\.part$|\.tmp$|\.uploading$|^thumbs\.db$)/i';

/** Quet cac thu muc -> (thu muc, {rel: [size, mtime, inode]}) - chua bam MD5. */
function scan_files($base, $dirs, $skip)
{
    $folders = array();
    $files   = array();
    $baseLen = strlen($base) + 1;
    foreach ($dirs as $d) {
        $root = $base . DIRECTORY_SEPARATOR . $d;
        if (!is_dir($root)) {
            continue;
        }
        $folders[] = $d;
        $it = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );
        foreach ($it as $path => $info) {
            if (preg_match($skip, $info->getFilename())) {
                continue;
            }
            $rel = str_replace('\\', '/', substr($path, $baseLen));
            if ($info->isDir()) {
                $folders[] = $rel;
            } elseif ($info->isFile()) {
                $files[$rel] = array($info->getSize(), $info->getMTime(), $info->getInode());
            }
        }
    }
    ksort($files, SORT_STRING);
    sort($folders, SORT_STRING);
    return array($folders, $files);
}

function load_cache($path)
{
    if (!is_file($path)) {
        return array();
    }
    $c = json_decode(@file_get_contents($path), true);
    return is_array($c) ? $c : array();
}

/** Tep nao chua co MD5 dung trong so (moi / doi co / doi mtime / doi inode). */
function stale_files($files, $cache)
{
    $out = array();
    foreach ($files as $rel => $st) {
        $c = isset($cache[$rel]) ? $cache[$rel] : null;
        if (!is_array($c) || !isset($c['md5']) || $c['s'] !== $st[0] || $c['m'] !== $st[1] || $c['i'] !== $st[2]) {
            $out[] = $rel;
        }
    }
    return $out;
}

list($folders, $files) = scan_files($BASE, $DIRS, $SKIP);
$cache = load_cache($CACHE);

if (stale_files($files, $cache)) {
    $lock = @fopen($CACHE . '.lock', 'c');
    if ($lock) {
        flock($lock, LOCK_EX);                 // tien trinh khac dang bam -> doi xong roi dung so cua no
    }
    $cache = load_cache($CACHE);
    clearstatcache();
    list($folders, $files) = scan_files($BASE, $DIRS, $SKIP);
    $todo = stale_files($files, $cache);
    foreach ($todo as $rel) {
        $st = $files[$rel];
        $h = @md5_file($BASE . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $rel));
        if ($h !== false) {
            $cache[$rel] = array('s' => $st[0], 'm' => $st[1], 'i' => $st[2], 'md5' => $h);
        }
    }
    foreach (array_keys($cache) as $rel) {      // tep da xoa khoi host -> bo khoi so
        if (!isset($files[$rel])) {
            unset($cache[$rel]);
        }
    }
    if ($todo) {
        $tmp = $CACHE . '.tmp';
        if (@file_put_contents($tmp, json_encode($cache)) !== false) {
            @rename($tmp, $CACHE);
        }
    }
    if ($lock) {
        flock($lock, LOCK_UN);
        fclose($lock);
    }
}

$out = '<?xml version="1.0" encoding="utf-8"?>' . "\n<AutoUpdate>\n";
foreach ($folders as $rel) {
    $out .= '  <Folder Name="' . htmlspecialchars($rel, ENT_QUOTES, 'UTF-8') . '" />' . "\n";
}
foreach ($files as $rel => $st) {
    if (!isset($cache[$rel]['md5'])) {
        continue;
    }
    $out .= '  <File Name="' . htmlspecialchars($rel, ENT_QUOTES, 'UTF-8') . '" MD5="' . $cache[$rel]['md5'] . '" />' . "\n";
}
$out .= "</AutoUpdate>\n";
header('Content-Length: ' . strlen($out));
echo $out;
