<?php
declare(strict_types=1);
function fail(string $m):never{fwrite(STDERR,$m.PHP_EOL);exit(1);}
function canon(mixed $v):mixed{if(!is_array($v))return $v;if(array_is_list($v))return array_map('canon',$v);ksort($v,SORT_STRING);foreach($v as $k=>$x)$v[$k]=canon($x);return $v;}
function keyFrom(string $p):string{if(!is_file($p))fail("Clé privée absente : ".$p);$r=(string)file_get_contents($p);if(strlen($r)===SODIUM_CRYPTO_SIGN_SECRETKEYBYTES)return $r;$d=base64_decode(trim($r),true);if(is_string($d)&&strlen($d)===SODIUM_CRYPTO_SIGN_SECRETKEYBYTES)return $d;if(is_string($d)&&strlen($d)===SODIUM_CRYPTO_SIGN_SEEDBYTES)return sodium_crypto_sign_secretkey(sodium_crypto_sign_seed_keypair($d));if(strlen($r)===SODIUM_CRYPTO_SIGN_SEEDBYTES)return sodium_crypto_sign_secretkey(sodium_crypto_sign_seed_keypair($r));fail("Format de clé non reconnu.");}
if(PHP_SAPI!=="cli"||!extension_loaded("sodium")||!class_exists(ZipArchive::class))fail("CLI, Sodium et Zip requis.");
$b=__DIR__;$s=$b.DIRECTORY_SEPARATOR."source";$root=rtrim((string)($argv[1]??dirname($b)),"\\/");$key=keyFrom($root.DIRECTORY_SEPARATOR."storage".DIRECTORY_SEPARATOR."private".DIRECTORY_SEPARATOR."update_signing_secret.key");$mp=$s.DIRECTORY_SEPARATOR."manifest.json";$m=json_decode((string)file_get_contents($mp),true);if(!is_array($m))fail("manifest invalide");$fs=[];$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($s,FilesystemIterator::SKIP_DOTS));foreach($it as $i){if(!$i->isFile())continue;$a=$i->getPathname();$r=str_replace("\\","/",substr($a,strlen($s)+1));if($r==="manifest.json")continue;$fs[]=["path"=>$r,"sha256"=>hash_file("sha256",$a)];}usort($fs,static fn($a,$b)=>strcmp($a["path"],$b["path"]));$m["files"]=$fs;unset($m["signature"]);$payload=json_encode(canon($m),JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);$m["signature"]=base64_encode(sodium_crypto_sign_detached($payload,$key));file_put_contents($mp,json_encode($m,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES).PHP_EOL);$out=$b.DIRECTORY_SEPARATOR."CDA_AXIOM_PLATFORM_023_3_5_1_PIPELINE_CORE_10.2.4.1_SIGNED_R1.zip";@unlink($out);$z=new ZipArchive();$z->open($out,ZipArchive::CREATE|ZipArchive::OVERWRITE);$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($s,FilesystemIterator::SKIP_DOTS));foreach($it as $i){if($i->isFile()){$a=$i->getPathname();$r=str_replace("\\","/",substr($a,strlen($s)+1));$z->addFile($a,$r);}}$z->close();echo "Package généré :".PHP_EOL.$out.PHP_EOL;
