#!/usr/bin/env php
<?php
// MCP command to zip core files and/or generate hash list
$targetDir = $argv[1] ?? __DIR__;
$zipFile = $argv[2] ?? (sys_get_temp_dir() . '/corefiles_' . uniqid() . '.zip');

$zip = new ZipArchive();
if ($zip->open($zipFile, ZipArchive::CREATE) !== true) {
    fwrite(STDERR, "Cannot open zip file: $zipFile\n");
    exit(1);
}

$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($targetDir));
foreach ($rii as $file) {
    if ($file->isDir()) continue;
    $relPath = str_replace($targetDir . '/', '', $file->getPathname());
    $zip->addFile($file->getPathname(), $relPath);
}
$zip->close();

// Optionally, generate hash list
$hashes = [];
foreach ($rii as $file) {
    if ($file->isDir()) continue;
    $relPath = str_replace($targetDir . '/', '', $file->getPathname());
    $hashes[$relPath] = hash_file('sha256', $file->getPathname());
}
file_put_contents($zipFile . '.hashes.json', json_encode($hashes, JSON_PRETTY_PRINT));

fwrite(STDOUT, "Zip file created: $zipFile\nHash file created: $zipFile.hashes.json\n");
