#!/home/interworx/bin/php
<?php
$cmd    = '~iworx/bin/ini.pex --get --section mysql --index home';
$output = [];

exec( $cmd, $output );

$data_dir = trim( $output[0] );

echo "Looking at databases in {$data_dir}, per iworx.ini\n";

$cmd    = '~iworx/bin/ini.pex --get --section mysql --index group_quota';
$output = [];

exec( $cmd, $output );

$group_quota = trim( $output[0] );

if( $group_quota === '1' ) {
  echo "Group quota is enabled, the group owner will be the siteworx user\n";
} else {
  echo "Group quota is disabled, the group owner will be the mysql user\n";
}

$Iterator = new DirectoryIterator( $data_dir );

foreach( $Iterator as $FileInfo ) {
  if( $FileInfo->isDir() === false || $FileInfo->isDot() ) {
    continue;
  }

  if(!str_contains($FileInfo->getFilename(), '_')) {
    continue;
  }

  if( $FileInfo->getFilename() === 'performance_schema' ) {
    continue;
  }

  echo "Found database: {$FileInfo->getFilename()}\n";

  if( $group_quota === '1' ) {
    $group = explode( '_', $FileInfo->getFilename() )[0];
  } else {
    $group = 'mysql';
  }

  echo "  Chowning to mysql:{$group}\n";

  $cmd = "chown --recursive mysql:{$group} {$FileInfo->getPathname()}";

  passthru( $cmd );

  echo "  Enforcing sticky bit for group\n";
  $cmd = "chmod g+s {$FileInfo->getPathname()}";

  passthru( $cmd );
}
