<?php

$storeRoot='/icebearstore/imagestore/';
$storeRoot='.';

include_once ('../../classes/core/Log.class.php');
Log::init(Log::LOGLEVEL_DEBUG);

Log::write(Log::LOGLEVEL_INFO, 'Begin processing...');
$files=scandir(__DIR__);
$now=time();
$buffer=20; //file must be this many seconds old before it will be processed.
foreach($files as $file){
    if(0!==stripos($file,'received_')){
        Log::write(Log::LOGLEVEL_DEBUG, 'Ignoring '.$file);
        continue;
    }$age=$now-filemtime($file);
    if($age<$buffer){
        Log::write(Log::LOGLEVEL_WARN, $file.' is '.$age.' seconds old. Needs to be '.$buffer.'.');
        Log::write(Log::LOGLEVEL_WARN, 'Not unpacking '.$file.' yet.');
        continue;
    }

    Log::write(Log::LOGLEVEL_WARN, 'Unpacking '.$file.' to '.$storeRoot.' ...');
    $resultCode=-1;
    system('tar xf '.$file.' -C '.$storeRoot, $resultCode);
    if(0===$resultCode){
        Log::write(Log::LOGLEVEL_INFO, '...done');
        Log::write(Log::LOGLEVEL_WARN, 'Deleting '.$file.'...');
        @unlink($file);
        Log::write(Log::LOGLEVEL_INFO, '...done');
    } else {
        Log::write(Log::LOGLEVEL_ERROR, 'Could not unpack '.$file);
        Log::write(Log::LOGLEVEL_ERROR, 'tar returned '.$resultCode);
    }

    Log::write(Log::LOGLEVEL_INFO, '-------------------------');
}
//foreach file,
//is it received*.tar?
//is it >5mins old?
//unpack

Log::write(Log::LOGLEVEL_INFO, 'Done.');
Log::write(Log::LOGLEVEL_INFO, '=========================');
