<?php

declare(strict_types=1);

$basePath = dirname(__DIR__);
$outputDir = $basePath . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'deploy';
$outputFile = $outputDir . DIRECTORY_SEPARATOR . 'mozcursos-cpanel.zip';

if (!class_exists(ZipArchive::class)) {
    fwrite(STDERR, "A extensao PHP zip nao esta activa.\n");
    exit(1);
}

if (!is_dir($outputDir)) {
    mkdir($outputDir, 0775, true);
}

if (file_exists($outputFile)) {
    unlink($outputFile);
}

$zip = new ZipArchive();
if ($zip->open($outputFile, ZipArchive::CREATE) !== true) {
    fwrite(STDERR, "Nao foi possivel criar {$outputFile}.\n");
    exit(1);
}

$exclude = [
    DIRECTORY_SEPARATOR . '.git' . DIRECTORY_SEPARATOR,
    DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'deploy' . DIRECTORY_SEPARATOR,
    DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'sessions' . DIRECTORY_SEPARATOR,
    DIRECTORY_SEPARATOR . 'mozcursos.zip',
];

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($basePath, FilesystemIterator::SKIP_DOTS)
);

foreach ($iterator as $file) {
    $path = $file->getPathname();
    $relative = ltrim(str_replace($basePath, '', $path), DIRECTORY_SEPARATOR);
    $normalized = DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $relative);

    foreach ($exclude as $item) {
        if (str_contains($normalized, $item)) {
            continue 2;
        }
    }

    if ($normalized === DIRECTORY_SEPARATOR . '.env') {
        continue;
    }

    if ($file->isFile()) {
        $zip->addFile($path, str_replace('\\', '/', $relative));
    }
}

$zip->close();

echo "Pacote criado: {$outputFile}\n";
