Files
Investidor-V2/outputs/investmoz-audit-current-20261012/activate-B-fresh-backup-20261015.php
T
nala c13f250b87
tests / ci (push) Canceled after 0s
versao compilada
2026-10-15 17:37:00 +02:00

52 lines
7.5 KiB
PHP

<?php
ini_set('zend.exception_ignore_args','1');
set_exception_handler(function(Throwable $e){fwrite(STDERR,'Fresh destination backup stopped: '.$e::class.' line '.$e->getLine().PHP_EOL);exit(1);});
$root=dirname(__DIR__,2);require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';
(new Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables)->bootstrap($app);(new Illuminate\Foundation\Bootstrap\LoadConfiguration)->bootstrap($app);
$c=config('database.connections.'.config('database.default'));
if($c['driver']!=='pgsql'||!empty($c['url'])||!in_array($c['host'],['127.0.0.1','localhost'])||(int)$c['port']!==5432||$c['database']!=='investemoz')throw new RuntimeException('Active identity mismatch');
$map=json_decode(file_get_contents(__DIR__.'/B-suplemento-C137-sequencia-final-20261015/MAPA-DISPONIBILIZACAO-REVERSAO.json'),true,512,JSON_THROW_ON_ERROR);
foreach($map['source_operations']as$op){$p=$root.'/'.$op['path'];if((is_file($p)?hash_file('sha256',$p):null)!==$op['before'])throw new RuntimeException('Source baseline changed');}
$stamp=gmdate('Ymd_His');$dir='C:/Users/macbook/.config/investmoz/B-active-before-'.$stamp;
if(is_dir($dir)||!mkdir($dir,0700,true))throw new RuntimeException('New backup directory required');
$restore='b_active_before_'.$stamp.'_test';
if(!preg_match('/^b_active_before_\d{8}_\d{6}_test$/D',$restore))throw new RuntimeException('Restore guard');
$source=new PDO('pgsql:host='.$c['host'].';port=5432;dbname=investemoz',$c['username'],$c['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);$source->exec('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');
$run=function(array$args,string$password){$p=new Symfony\Component\Process\Process($args,null,['PGPASSWORD'=>$password]);$p->setTimeout(240);$p->run();if(!$p->isSuccessful())throw new RuntimeException('Backup or restore subprocess failed');};
try{
$identity=$source->query('SELECT current_database() AS database,inet_server_port() AS port')->fetch(PDO::FETCH_ASSOC);
if($identity['database']!=='investemoz'||(int)$identity['port']!==5432)throw new RuntimeException('Actual active mismatch');
$migration=$source->query("SELECT count(*) FROM migrations WHERE migration='2026_10_09_190000_prepare_investor_path'")->fetchColumn();
$env=Dotenv\Dotenv::parse(file_get_contents($root.'/.env'));
if(filter_var($env['INVESTOR_PATH_ENABLED']??false,FILTER_VALIDATE_BOOL))throw new RuntimeException('Path must remain disabled');
$snapshot=$source->query('SELECT pg_export_snapshot()')->fetchColumn();$dump=$dir.'/destination.dump';$bin='C:/Program Files/PostgreSQL/17/bin/';
$run([$bin.'pg_dump.exe','-h',$c['host'],'-p','5432','-U',$c['username'],'-d','investemoz','-Fc','--snapshot='.$snapshot,'-f',$dump],$c['password']);
$admin=new PDO('pgsql:host=127.0.0.1;port=55441;dbname=postgres','postgres','',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
if((int)$admin->query('SELECT inet_server_port()')->fetchColumn()!==55441)throw new RuntimeException('QA restore identity');
$admin->exec('CREATE DATABASE "'.$restore.'"');
$run([$bin.'pg_restore.exe','-h','127.0.0.1','-p','55441','-U','postgres','-d',$restore,'--exit-on-error','--no-owner','--no-privileges',$dump],'');
$clone=new PDO('pgsql:host=127.0.0.1;port=55441;dbname='.$restore,'postgres','',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);$clone->exec('BEGIN READ ONLY');
$tables=[];foreach($source->query("SELECT schemaname,tablename FROM pg_tables WHERE schemaname NOT IN ('pg_catalog','information_schema') ORDER BY schemaname,tablename")->fetchAll(PDO::FETCH_ASSOC)as$t){
$name='"'.str_replace('"','""',$t['schemaname']).'"."'.str_replace('"','""',$t['tablename']).'"';$sql='SELECT row_to_json(t)::text FROM '.$name.' t ORDER BY row_to_json(t)::text';
$a=$source->query($sql)->fetchAll(PDO::FETCH_COLUMN);$b=$clone->query($sql)->fetchAll(PDO::FETCH_COLUMN);if($a!==$b)throw new RuntimeException('Restored rows differ');$tables[$name]=['rows'=>count($a),'sha256'=>hash('sha256',implode("\n",$a))];
}
$sql="SELECT schemaname,sequencename,data_type,start_value,min_value,max_value,increment_by,cycle,cache_size,last_value FROM pg_sequences WHERE schemaname NOT IN ('pg_catalog','information_schema') ORDER BY schemaname,sequencename";
$sequences=$source->query($sql)->fetchAll(PDO::FETCH_ASSOC);if($sequences!==$clone->query($sql)->fetchAll(PDO::FETCH_ASSOC))throw new RuntimeException('Sequence mismatch');
$zip=new ZipArchive();$fileszip=$dir.'/destination-files.zip';if($zip->open($fileszip,ZipArchive::CREATE|ZipArchive::EXCL)!==true)throw new RuntimeException('Private files archive');
$files=[];$copy=function(string$from,string$rel)use($dir,$zip,&$files){$to=$dir.'/files/'.$rel;$restored=$dir.'/file-restore/'.$rel;foreach([$to,$restored]as$p){if(!is_dir(dirname($p)))mkdir(dirname($p),0700,true);if(!copy($from,$p)||hash_file('sha256',$from)!==hash_file('sha256',$p))throw new RuntimeException('File restore mismatch');}$files[$rel]=hash_file('sha256',$from);$zip->addFile($to,$rel);};
foreach($map['source_operations']as$op)if(is_file($root.'/'.$op['path']))$copy($root.'/'.$op['path'],$op['path']);
$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root.'/public/build',FilesystemIterator::SKIP_DOTS));foreach($it as$f)if($f->isFile())$copy($f->getPathname(),str_replace('\\','/',substr($f->getPathname(),strlen($root)+1)));
foreach(['.env','config/inertia.php','config/investor-path.php','composer.lock','package-lock.json','bootstrap/app.php']as$n)$copy($root.'/'.$n,$n);
$local=config('filesystems.disks.local.root');$docs=0;$unavailable=[];
foreach($source->query('SELECT id,storage_key,status,deleted_at FROM documents WHERE storage_key IS NOT NULL ORDER BY id')->fetchAll(PDO::FETCH_ASSOC)as$d){
$p=$local.'/'.$d['storage_key'];if(!is_file($p)){$unavailable[]=['id'=>$d['id'],'status'=>$d['status'],'deleted'=>$d['deleted_at']!==null];continue;}
$copy($p,'storage-documents/'.$d['id'].'.stored');$docs++;
}
$zip->close();$clone->exec('ROLLBACK');
$private=['verified_at'=>gmdate('c'),'target'=>$identity,'restore_target'=>['database'=>$restore,'port'=>55441],'dump_path'=>$dump,'sha256'=>hash_file('sha256',$dump),'files_path'=>$fileszip,'files_sha256'=>hash_file('sha256',$fileszip),'restore_verified'=>true,'files_verified'=>true,'tables'=>$tables,'sequence_count'=>count($sequences),'file_hashes'=>$files,'preexisting_unavailable_documents'=>$unavailable,'source_paths'=>$map['source_operations'],'path_flag_before'=>false,'190000_before'=>(int)$migration,'active_business_writes'=>0];
file_put_contents($dir.'/backup-proof-private.json',json_encode($private,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR));
$safe=['at'=>$private['verified_at'],'candidate'=>'B-final-fabf722bc8c6','C137_included'=>true,'target'=>$identity,'restore_target'=>$private['restore_target'],'restore_verified'=>true,'files_verified'=>true,'tables'=>count($tables),'sequences'=>count($sequences),'restored_table_hashes_equal'=>true,'private_directory'=>$dir,'dump_sha256'=>$private['sha256'],'files_sha256'=>$private['files_sha256'],'file_count'=>count($files),'document_files'=>$docs,'preexisting_unavailable_document_count'=>count($unavailable),'190000_before'=>(int)$migration,'path_flag_before'=>false,'active_business_writes'=>0];
if(is_file(__DIR__.'/B-activation-fresh-backup-20261015.json'))throw new RuntimeException('Preserve receipt');
file_put_contents(__DIR__.'/B-activation-fresh-backup-20261015.json',json_encode($safe,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR).PHP_EOL);echo json_encode($safe,JSON_UNESCAPED_UNICODE).PHP_EOL;
}finally{$source->exec('ROLLBACK');}