#!/usr/bin/env php
<?php
/**
 * cli_create_stubs.php — Crea stubs (archivos 0 bytes) en data/media/ de cada wiki
 *
 * Lee los media_id de cada wasabisync.sqlite3 y crea archivos vacíos
 * en la ruta correspondiente de data/media/ para que DokuWiki los reconozca.
 * El plugin wasabisync intercepta la descarga y redirige a Wasabi.
 *
 * Uso: php cli_create_stubs.php
 *
 * Seguro: solo crea archivos vacíos y directorios. No borra nada.
 */

if (php_sapi_name() !== 'cli') {
    die('Solo CLI');
}

$BASE_DIR = '/home/systeng3/public_html';

// =====================================================================
//  Detectar wikis (misma lógica que cli_all.php)
// =====================================================================
function detectWikis($baseDir) {
    $wikis = [];
    $baseDir = rtrim($baseDir, '/');
    $handle = @opendir($baseDir);
    if (!$handle) return $wikis;

    while (($entry = readdir($handle)) !== false) {
        if ($entry[0] === '.') continue;
        $path = $baseDir . '/' . $entry;
        if (!is_dir($path)) continue;
        if (file_exists($path . '/doku.php')) {
            $wikis[] = [
                'id'   => $entry,
                'path' => $path,
            ];
        }
    }
    closedir($handle);
    sort($wikis);
    return $wikis;
}

// =====================================================================
//  Crear stubs para un wiki
// =====================================================================
function createStubsForWiki($wikiPath, $wikiId) {
    $dbFile = $wikiPath . '/data/meta/wasabisync.sqlite3';
    if (!file_exists($dbFile)) {
        return ['status' => 'skip', 'reason' => 'no sqlite', 'created' => 0, 'existed' => 0, 'errors' => 0];
    }

    try {
        $pdo = new PDO('sqlite:' . $dbFile);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (Exception $e) {
        return ['status' => 'error', 'reason' => 'sqlite open: ' . $e->getMessage(), 'created' => 0, 'existed' => 0, 'errors' => 0];
    }

    // Leer todos los media_id
    try {
        $stmt = $pdo->query('SELECT media_id FROM wasabi_files');
        $rows = $stmt->fetchAll(PDO::FETCH_COLUMN);
    } catch (Exception $e) {
        return ['status' => 'error', 'reason' => 'query: ' . $e->getMessage(), 'created' => 0, 'existed' => 0, 'errors' => 0];
    }

    if (empty($rows)) {
        return ['status' => 'empty', 'reason' => '0 registros', 'created' => 0, 'existed' => 0, 'errors' => 0];
    }

    $mediaDir = $wikiPath . '/data/media';
    $created = 0;
    $existed = 0;
    $errors  = 0;

    foreach ($rows as $mediaId) {
        // Convertir media_id (separador :) a ruta de archivo (separador /)
        $relativePath = str_replace(':', '/', $mediaId);
        $fullPath = $mediaDir . '/' . $relativePath;

        // Si ya existe (stub o con contenido), saltar
        if (file_exists($fullPath)) {
            $existed++;
            continue;
        }

        // Crear directorio padre si no existe
        $dir = dirname($fullPath);
        if (!is_dir($dir)) {
            if (!@mkdir($dir, 0755, true)) {
                $errors++;
                continue;
            }
        }

        // Crear archivo vacío (stub de 0 bytes)
        if (@touch($fullPath)) {
            $created++;
        } else {
            $errors++;
        }
    }

    return [
        'status'  => 'ok',
        'reason'  => '',
        'total'   => count($rows),
        'created' => $created,
        'existed' => $existed,
        'errors'  => $errors,
    ];
}

// =====================================================================
//  MAIN
// =====================================================================

$startTime = microtime(true);

$wikis = detectWikis($BASE_DIR);
$wikiCount = count($wikis);

echo "╔══════════════════════════════════════════════════╗\n";
echo "║  CREAR STUBS (0 bytes) EN DATA/MEDIA             ║\n";
echo "╠══════════════════════════════════════════════════╣\n";
echo "║  Wikis detectados: " . str_pad($wikiCount, 29) . "║\n";
echo "║  Fecha: " . date('Y-m-d H:i:s') . str_pad('', 18) . "║\n";
echo "╚══════════════════════════════════════════════════╝\n";

$totalCreated = 0;
$totalExisted = 0;
$totalErrors  = 0;
$wikisOk      = 0;
$wikisSkip    = 0;
$wikisError   = 0;

foreach ($wikis as $i => $wiki) {
    $num = $i + 1;
    $ts = date('H:i:s');

    $result = createStubsForWiki($wiki['path'], $wiki['id']);

    switch ($result['status']) {
        case 'ok':
            $wikisOk++;
            $totalCreated += $result['created'];
            $totalExisted += $result['existed'];
            $totalErrors  += $result['errors'];
            echo "[$ts] [$num/$wikiCount] {$wiki['id']} — "
                . "{$result['created']} creados, {$result['existed']} existían"
                . ($result['errors'] > 0 ? ", {$result['errors']} errores" : '')
                . "\n";
            break;

        case 'empty':
            $wikisSkip++;
            echo "[$ts] [$num/$wikiCount] {$wiki['id']} — vacío (0 registros)\n";
            break;

        case 'skip':
            $wikisSkip++;
            echo "[$ts] [$num/$wikiCount] {$wiki['id']} — sin SQLite (skip)\n";
            break;

        case 'error':
            $wikisError++;
            echo "[$ts] [$num/$wikiCount] {$wiki['id']} — ERROR: {$result['reason']}\n";
            break;
    }
}

$elapsed = round(microtime(true) - $startTime, 1);

echo "╔══════════════════════════════════════════════════╗\n";
echo "║  RESULTADO STUBS                                 ║\n";
echo "╠══════════════════════════════════════════════════╣\n";
echo "║  Wikis procesados: " . str_pad($wikisOk, 29) . "║\n";
echo "║  Wikis sin datos:  " . str_pad($wikisSkip, 29) . "║\n";
echo "║  Wikis con error:  " . str_pad($wikisError, 29) . "║\n";
echo "║  Stubs creados:    " . str_pad(number_format($totalCreated), 29) . "║\n";
echo "║  Ya existían:      " . str_pad(number_format($totalExisted), 29) . "║\n";
echo "║  Errores archivo:  " . str_pad(number_format($totalErrors), 29) . "║\n";
echo "║  Tiempo:           " . str_pad($elapsed . 's', 29) . "║\n";
echo "╚══════════════════════════════════════════════════╝\n";
