1. <?php
  2. /**
  3. * Archives directory content for dry-run scenarios based on a configuration file.
  4. *
  5. * @param array $config Configuration array.
  6. * - 'source_directories' => Array of directories to archive.
  7. * - 'archive_dir' => Directory to store the archives.
  8. * - 'dry_run' => Whether to perform a dry run (true) or actually archive (false).
  9. */
  10. function archiveDirectories(array $config): void
  11. {
  12. // Validate configuration
  13. if (!isset($config['source_directories']) || !is_array($config['source_directories']) || empty($config['source_directories'])) {
  14. error_log("Invalid 'source_directories' configuration.");
  15. return;
  16. }
  17. if (!isset($config['archive_dir']) || !is_dir($config['archive_dir'])) {
  18. error_log("Invalid 'archive_dir' configuration.");
  19. return;
  20. }
  21. if (!isset($config['dry_run']) || !is_bool($config['dry_run'])) {
  22. error_log("Invalid 'dry_run' configuration.");
  23. return;
  24. }
  25. $sourceDirectories = $config['source_directories'];
  26. $archiveDir = $config['archive_dir'];
  27. $dryRun = $config['dry_run'];
  28. // Ensure archive directory exists
  29. if (!is_dir($archiveDir)) {
  30. try {
  31. mkdir($archiveDir, 0777, true); // Create directory recursively
  32. } catch (Exception $e) {
  33. error_log("Failed to create archive directory: " . $e->getMessage());
  34. return;
  35. }
  36. }
  37. foreach ($sourceDirectories as $sourceDir) {
  38. if (!is_dir($sourceDir)) {
  39. error_log("Source directory does not exist: " . $sourceDir);
  40. continue;
  41. }
  42. $archiveName = basename($sourceDir);
  43. $archivePath = $archiveDir . '/' . $archiveName . '.tar.gz';
  44. if ($dryRun) {
  45. echo "Dry Run: Archiving $sourceDir to $archivePath\n";
  46. } else {
  47. // Use tar command to create the archive
  48. $command = "tar -czvf " . escapeshellarg($archivePath) . " -C " . escapeshellarg($sourceDir) . " .";
  49. exec($command, $output, $returnCode);
  50. if ($returnCode !== 0) {
  51. error_log("Failed to archive $sourceDir. Return code: " . $returnCode . ". Output: " . implode("\n", $output));
  52. } else {
  53. echo "Archived $sourceDir to $archivePath\n";
  54. }
  55. }
  56. }
  57. }
  58. // Example Usage (read config from a file, for example)
  59. // $config = parse_ini_file('config.ini');
  60. // archiveDirectories($config);
  61. ?>

Add your comment