<?php
// READ creds from wp-config, full mysqldump. Usage: BDIR=... php _dump_db.php /site/dir
$dir=rtrim($argv[1]??'','/');$cfg=$dir.'/wp-config.php';
if(!is_file($cfg)){fwrite(STDERR,"no wp-config: $dir\n");exit(2);}
$s=file_get_contents($cfg);
function gc($s,$k){return preg_match('/define\(\s*[\x27\x22]'.$k.'[\x27\x22]\s*,\s*[\x27\x22]([^\x27\x22]*)/',$s,$m)?$m[1]:'';}
$host=gc($s,'DB_HOST');$user=gc($s,'DB_USER');$pass=gc($s,'DB_PASSWORD');$name=gc($s,'DB_NAME');
$port=0;if(strpos($host,':')!==false){list($host,$port)=explode(':',$host,2);$port=(int)$port;}
$port=$port?:3306;$site=basename($dir);$bdir=getenv('BDIR');
putenv("MYSQL_PWD=$pass");
$out=$bdir."/".$site."-2026-06-23.sql";
$cmd="mysqldump -h ".escapeshellarg($host)." -P ".(int)$port." -u ".escapeshellarg($user)." --single-transaction --no-tablespaces --skip-lock-tables ".escapeshellarg($name)." > ".escapeshellarg($out)." 2>/tmp/dumperr_$site";
system($cmd,$rc);$sz=is_file($out)?filesize($out):0;
printf("  %-16s -> %d o (rc=%d)%s\n",$site,$sz,$rc,$sz<2000?(" ERR:".trim(@file_get_contents("/tmp/dumperr_$site"))):"");
