<?php
// slideshow_cleanup.php
// RJM Programming
// May, 2022

  $cdis=dirname(__FILE__) . DIRECTORY_SEPARATOR;
  exec("cd " . $cdis . "; find . -name 'slideshow_0.zip' 2> /dev/null > /tmp/slideshow_cleanup.txt");
  
  $lines = file('/tmp/slideshow_cleanup.txt');
  date_default_timezone_set('Australia/Perth');


  foreach ($lines as $line_num => $line) {
    $ji=0;
    if (substr($line,0,1) == '.') { $ji=2; }
    //echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
    $thisdir=explode('slideshow_0.zip', $line)[0];
    //echo "unzip -l " . $cdis . substr($line, $ji) . " > /tmp/slideshow_cleanup.cnt \n";
    $uzc=shell_exec("unzip -l " . $cdis . substr($line, $ji));
    //echo "\n" . $uzc . "\n";
    //file_put_contents("/tmp/slideshow_cleanup.cnt", $outs);
    //$uzc=file_get_contents('/tmp/slideshow_cleanup.cnt');
    foreach (glob($thisdir . '*-[0-9]*of.[jJpPgG][pPnNiI]*') as $zipmember) {
      $ij=0;
      if (substr($zipmember,0,1) == '.') { $ij=2; }
      $thisfile=$cdis . substr($zipmember, $ij);
      if (strpos($uzc, (' ' . explode(DIRECTORY_SEPARATOR,   substr($zipmember, $ij))[-1 + sizeof(explode(DIRECTORY_SEPARATOR,   substr($zipmember, $ij)))])    ) !== false) {
        if ((time() - filectime($thisfile)) > 600) {   // more than 10 minutes old
          //file_put_contents('/tmp/slideshow_cleanup.txt', file_get_contents('/tmp/slideshow_cleanup.txt') . "\nunlink(" . $thisfile . ")\n"); //unlink($thisfile); //echo "analyze " . $thisfile . " " . (time() - filectime($thisfile)) . ' seconds ago ' . "\n";
          unlink($thisfile); //echo "analyze " . $thisfile . " " . (time() - filectime($thisfile)) . ' seconds ago ' . "\n";
        } //else {
          //echo "too recent ... analyze " . $thisfile . " " . (time() - filectime($thisfile)) . ' seconds ago ' . "\n";
        //}
      }
    }
    foreach (glob($thisdir . '*-[0-9]{[0-9]*}.[jJpPgG][pPnNiI]*') as $zipmember) {
      $ij=0;
      if (substr($zipmember,0,1) == '.') { $ij=2; }
      $thisfile=$cdis . substr($zipmember, $ij);
      if (strpos($uzc, (' ' . explode(DIRECTORY_SEPARATOR,   substr($zipmember, $ij))[-1 + sizeof(explode(DIRECTORY_SEPARATOR,   substr($zipmember, $ij)))])    ) !== false) {
        if ((time() - filectime($thisfile)) > 600) {
          //file_put_contents('/tmp/slideshow_cleanup.txt', file_get_contents('/tmp/slideshow_cleanup.txt') . "\nunlink(" . $thisfile . ")\n"); //unlink($thisfile); //echo "Analyze " . $thisfile . " " . (time() - filectime($thisfile)) . ' seconds ago ' . "\n";
          unlink($thisfile); //echo "Analyze " . $thisfile . " " . (time() - filectime($thisfile)) . ' seconds ago ' . "\n";
        } //else {
          //echo "too recent ... Analyze " . $thisfile . " " . (time() - filectime($thisfile)) . ' seconds ago ' . "\n";
        //}
      }
    }
  }  

?>
