Files
Investidor-V2/outputs/investmoz-parques-ativacao-20261016/fresh-backup.php
T
nala cef6e201c7
tests / ci (push) Canceled after 0s
versao nrgocios 2
2026-10-16 20:11:05 +02:00

66 lines
11 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);$release=$root.'/outputs/investmoz-parques-QA-20261016';$manifest=json_decode(file_get_contents($release.'/para-revisao/MANIFESTO-CANDIDATA.json'),true,512,JSON_THROW_ON_ERROR);if(($argv[1]??'')!=='--candidate='.$manifest['candidate'])throw new RuntimeException('Exact candidate argument required');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=['source_operations'=>array_map(fn($p)=>['path'=>$p['path'],'active_before_sha256'=>$p['before_sha256']],$manifest['sources'])];
foreach($map['source_operations']as$op){$p=$root.'/'.$op['path'];if((is_file($p)?hash_file('sha256',$p):null)!==$op['active_before_sha256'])throw new RuntimeException('Source baseline changed; reconcile before delivery');}
$cacheState=['configuration_cached'=>$app->configurationIsCached(),'routes_cached'=>is_file($app->getCachedRoutesPath()),'views_precompiled'=>false,'views_mode_evidence'=>'Previous installed delivery used view:clear only; views are compiled on request','configuration_path'=>$app->getCachedConfigPath(),'routes_path'=>$app->getCachedRoutesPath(),'compiled_views_path'=>config('view.compiled'),'data_cache_store'=>config('cache.default'),'data_cache_file_path'=>config('cache.stores.file.path')];
$views=str_replace('\\','/',(string)realpath((string)$cacheState['compiled_views_path']));$data=str_replace('\\','/',(string)realpath((string)$cacheState['data_cache_file_path']));
if($views!==str_replace('\\','/',$root).'/storage/framework/views'||($data&&($views===$data||str_starts_with($data,$views.'/'))))throw new RuntimeException('Compiled views must be exclusive and separate from data cache');
if($cacheState['configuration_cached']||$cacheState['routes_cached']||$cacheState['views_precompiled'])throw new RuntimeException('Unexpected cache mode; reconcile destination before delivery');
$stamp=gmdate('Ymd_His');$dir='C:/Users/macbook/.config/investmoz/parks-before-'.$stamp;
if(is_dir($dir)||!mkdir($dir,0700,true))throw new RuntimeException('New backup directory required');
$restore='parks_before_'.$stamp.'_test';
if(!preg_match('/^parks_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');$source->exec("SET LOCAL TIME ZONE 'UTC'");
$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();
$state=['ledger'=>(int)$source->query("SELECT count(*) FROM migrations WHERE migration='2026_10_16_130000_add_investment_zone_editorial_draft'")->fetchColumn(),'column'=>(int)$source->query("SELECT count(*) FROM information_schema.columns WHERE table_schema='public' AND table_name='investment_zones' AND column_name='editorial_draft'")->fetchColumn(),'economic_migration'=>(int)$source->query("SELECT count(*) FROM migrations WHERE migration='2026_10_16_120000_extend_economic_reference_hierarchy'")->fetchColumn()];
if($state!==['ledger'=>0,'column'=>0,'economic_migration'=>1])throw new RuntimeException('Unexpected parks schema state; reconcile before delivery');
file_put_contents(__DIR__.'/PREFLIGHT-ESQUEMA.json',json_encode(['at'=>gmdate('c'),'read_only'=>true,'schema'=>$state],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR).PHP_EOL);
$env=Dotenv\Dotenv::parse(file_get_contents($root.'/.env'));
if(!filter_var($env['INVESTOR_PATH_ENABLED']??false,FILTER_VALIDATE_BOOL)||!filter_var($env['PORTAL_LEGACY_CONTENT_ENABLED']??false,FILTER_VALIDATE_BOOL))throw new RuntimeException('Both flags must remain enabled');
$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');$clone->exec("SET LOCAL TIME ZONE 'UTC'");
$tables=[];foreach($source->query("SELECT schemaname,tablename FROM pg_tables WHERE schemaname NOT LIKE 'pg_%' AND schemaname <> '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 LIKE 'pg_%' AND schemaname <> '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);};
$baselineData=json_decode(file_get_contents($release.'/ATIVO-ANTES.json'),true,512,JSON_THROW_ON_ERROR);$baseline=array_merge($baselineData['files'],$baselineData['protected']);
foreach($baseline as$path=>$hash){if(!is_file($root.'/'.$path)||hash_file('sha256',$root.'/'.$path)!==$hash)throw new RuntimeException('Protected baseline differs');$copy($root.'/'.$path,$path);}
foreach(['bootstrap','config']as$folder){$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root.'/'.$folder,FilesystemIterator::SKIP_DOTS));foreach($it as$f)if($f->isFile()){$rel=str_replace('\\','/',substr($f->getPathname(),strlen($root)+1));if(!isset($files[$rel]))$copy($f->getPathname(),$rel);}}
foreach(['artisan','composer.json','package.json','tsconfig.json']as$n)$copy($root.'/'.$n,$n);
foreach(['storage/app/public','storage/app/private/land-assistance','storage/app/private/opportunity-resources','storage/app/private/partnership-exchange','storage/app/private/partnerships','storage/app/private/portal-documents','storage/app/private/virtual-desk','storage/app/private/ai-documents','storage/app/private/investment-zones']as$folder){if(!is_dir($root.'/'.$folder))continue;$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root.'/'.$folder,FilesystemIterator::SKIP_DOTS));foreach($it as$f)if($f->isFile()){$rel=str_replace('\\','/',substr($f->getPathname(),strlen($root)+1));if(!isset($files[$rel]))$copy($f->getPathname(),$rel);}}
$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'],'cache_state'=>$cacheState,'B_path_flag_before'=>true,'legacy_reader_before'=>true,'190000_before'=>(int)$migration,'active_business_writes'=>0,'cache_state'=>$cacheState];
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'=>$manifest['candidate'],'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,'cache_state'=>$cacheState,'B_path_flag_before'=>true,'legacy_reader_before'=>true,'active_business_writes'=>0,'cache_state'=>$cacheState];
if(is_file(__DIR__.'/FRESH-BACKUP.json'))throw new RuntimeException('Preserve receipt');
file_put_contents(__DIR__.'/FRESH-BACKUP.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');}