<?php
/**
 * Gradually pushes all imagingsession images to a remote server.
 * Assumes import has stopped on this server, and needs a list of imaging session IDs.
 * SELECT id from imagingsession, then remove all formatting leaving one ID per line,
 * save into the same directory as this file wih name "imagingSessionIds".
 */

$safety=0; //Don't import the last X inspections - might not be complete.
$perRun=20; //How many sets of images to copy at once.
$storePath='/mnt/minstrel/'; //local
$domain='https://ZZZZ.icebox.icebear.fi'; //destination
$maxTarMegabytes=7;
chdir(__DIR__);

if(file_exists('lockfile')){ die('Lock file exists, aborting'); }
touch('lockfile');

set_time_limit(0);
ini_set('memory_limit','1024M');

$imagingSessionIdsFile=@file_get_contents('imagingSessionIds');
if(!$imagingSessionIdsFile){
    die('Cannot get list of imaging session IDs');
}
$imagingSessionIds=explode("\n",trim($imagingSessionIdsFile));
$imagingSessionIds=array_slice($imagingSessionIds,$safety);

$isFirstRun=false;
$minImagingSessionId=@file_get_contents('minImagingSessionId');
if(false===$minImagingSessionId){
    $isFirstRun=true;
}

if($isFirstRun){
    $minImagingSessionIndex=0;
    echo "First run,index 0\n";
} else {
    $minImagingSessionIndex=array_search($minImagingSessionId, $imagingSessionIds);
    echo "Not first run, index $minImagingSessionIndex";
}

//define class autoloader
spl_autoload_register(function($className){
    global $projectWebsiteEnabled;
    $paths=array(
        '../../classes/',
        '../../classes/core/',
        '../../classes/core/exception/',
        '../../classes/core/authentication/',
        '../../classes/core/interface/',
        '../../classes/model/',
    );
    foreach($paths as $path){
        if(file_exists($path.$className.'.class.php')){
			include_once($path.$className.'.class.php');
        }
    }
});


//connect to the database

try {
    database::connect();
    database::begin();
    session::init(new DummySession());
    session::becomeAdmin();
    Log::init(Log::LOGLEVEL_DEBUG);

    $result=array_slice($imagingSessionIds, $minImagingSessionIndex+1, $perRun);

    if(empty($result)){
        Log::write(Log::LOGLEVEL_WARN, 'Nothing to do');
    } else {

        $sql='SELECT d1.imagingsessionid AS imagingsessionid, d1.imagepath, d1.thumbnailpath, d1.imagestorepath
                    FROM dropimage AS d1
                    WHERE d1.imagestorepath="'.$storePath.'"
                    AND d1.imagingsessionid IN('.implode(',',$result).')
                    AND d1.imagepath<>"dummyimage.jpg"
                    AND d1.imagepath<>"dummythumb.jpg"
                    ORDER BY d1.imagepath';

        $images=database::queryGetAll($sql);

        if(null==$images){
            Log::write(Log::LOGLEVEL_WARN,'No images for these imaging sessions');
        } else {
            $images = $images['rows'];
            Log::write(Log::LOGLEVEL_INFO, count($images) . ' images found');

            //Package up the images into tar files, subject to filesize limit
            $count = 0;
            $maxTarBytes = $maxTarMegabytes * 1024 * 1024;
            foreach ($images as $image) {
                if (filesize($image['imagestorepath'] . $image['imagepath']) + filesize($image['imagestorepath'] . $image['thumbnailpath']) + filesize('images-' . $count . '.tar') > $maxTarBytes) {
                    Log::write(Log::LOGLEVEL_INFO, 'images-'.$count.'.tar is '.filesize('images-'.$count.'.tar').' bytes');
                    $count++;
                }
                if(file_exists($image['imagestorepath']. $image['imagepath']) && file_exists($image['imagestorepath'].$image['thumbnailpath'])){
                    system('tar -rf images-' . $count . '.tar -C ' . $image['imagestorepath'] .' '. $image['imagepath']);
                    system('tar -rf images-' . $count . '.tar -C ' . $image['imagestorepath'] .' '. $image['thumbnailpath']);
                }
            }

            //Send the TARs file to the other server
            $count = 0;
            $filename='images-'.$count.'.tar';
            while(file_exists($filename)){

                $data=file_get_contents($filename);
                $handle = curl_init(rtrim($domain,'/') . "/api/imagepush/receive.php");
                curl_setopt($handle, CURLOPT_POST, true);
                curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
                Log::info("Sending $filename, length=".strlen($data));
                $content=curl_exec($handle);
                $info=curl_getinfo($handle);
//              Log::info($content);
                @unlink($filename);


                $count++;
                $filename='images-'.$count.'.tar';

            }
        }

        $minImagingSessionId=end($result);
        Log::info( 'Minimum imaging session ID '.$minImagingSessionId);
        $fh2=@fopen('minImagingSessionId','wb');
        if(!$fh2 || false===@fwrite($fh2, "".$minImagingSessionId) || !@fclose($fh2)){
            throw new Exception('Could not write min file');
        }
    }

    @unlink('lockfile');

} catch (Exception $e){
    var_dump($e);
}

database::abort();




