<?php
mysqli_report(MYSQLI_REPORT_OFF);
$mode=$argv[1];
$site='amar';
$c=@file_get_contents(getenv('HOME')."/$site/wp-config.php");
if($c===false){fwrite(STDERR,"pas de wp-config amar\n");exit(1);}
$g=function($k)use($c){return preg_match("/define\(\s*['\"]".$k."['\"]\s*,\s*['\"]([^'\"]*)/",$c,$m)?$m[1]:'';};
if(!preg_match('/\$table_prefix\s*=\s*[\'"]([^\'"]+)[\'"]/',$c,$m)){fwrite(STDERR,"prefix introuvable -> ABORT\n");exit(1);}
$p=$m[1];
if($p===''||$p==='wp_'){fwrite(STDERR,"prefix suspect ($p) -> ABORT\n");exit(1);}
$hp=explode(':',$g('DB_HOST'));
$db=@mysqli_connect($hp[0],$g('DB_USER'),$g('DB_PASSWORD'),$g('DB_NAME'),isset($hp[1])?(int)$hp[1]:3306);
if(!$db){fwrite(STDERR,"DB KO\n");exit(1);}
$all=[]; $r=mysqli_query($db,"SHOW TABLES"); while($r&&($x=mysqli_fetch_row($r)))$all[]=$x[0];
$mine=array_values(array_filter($all,function($t)use($p){return strpos($t,$p)===0;}));
if($mode==='list'){ echo implode(' ',$mine); exit(0); }
if($mode==='drop'){
  if(!in_array($p.'options',$all)||!in_array($p.'users',$all)){fwrite(STDERR,"tables coeur ($p) absentes -> ABORT drop\n");exit(1);}
  $n=0; foreach($mine as $t){ if(mysqli_query($db,"DROP TABLE `$t`")) $n++; }
  echo "  drop $n tables (prefixe $p)\n"; exit(0);
}
