<?php 

error_reporting(E_ALL);
ini_set("display_errors", 1);

define("IEM_CRON_JOB", true);
define("IEM_NO_CONTROLLER", true);
define("IEM_CLI_MODE", true);

//require_once dirname(dirname(dirname(dirname("")))) . "/index.php"; // LOL
require_once dirname(dirname(dirname(dirname(__FILE__)))) . "/index.php";
require_once IEM_PUBLIC_PATH . "/functions/api/settings.php";

$settings_api = new Settings_API();
if( $settings_api->NeedDatabaseUpgrade() ) {    
    exit;
}
unset($settings_api);

if( !SENDSTUDIO_SAFE_MODE && strpos(SENDSTUDIO_DISABLED_FUNCTIONS, "set_time_limit") === false ) {    
    set_time_limit(0);
}

if( !defined("SENDSTUDIO_IS_SETUP") || !SENDSTUDIO_IS_SETUP ) {    
    exit;
}

require_once SENDSTUDIO_FUNCTION_DIRECTORY . "/sendstudio_functions.php";

$path = IEM_ADDONS_PATH . "/multithread/api/multithread.php";
if( !is_file($path) ) {    
    return false;
}

require_once $path;
require_once IEM_ADDONS_PATH . "/multithread/api/commandline.php";

$api = new Multithread_API();
$options = CommandLine::parseArgs($argv);

if( isset( $options["queue-info"] ) ) {    
    $jobid = isset( $options["jobid"] ) ? $options["jobid"] : 0;
    $api->tool_queue_info($jobid);
}

if( isset( $options["queue-rebuild"] ) ) {    
    $jobid = isset( $options["jobid"] ) ? $options["jobid"] : 0;
    $api->tool_queue_rebuild($jobid);
}

if( isset( $options["job-free-threads"] ) ) {
    
    $jobid = isset( $options["jobid"] ) ? $options["jobid"] : 0;
    $api->tool_job_free_threads($jobid);
}

if( isset( $options["job-rebuild-threads"] ) ) {    
    $jobid = isset( $options["jobid"] ) ? $options["jobid"] : 0;
    $threads = isset( $options["threads"] ) ? $options["threads"] : 10;
    $emails = isset( $options["emails"] ) ? $options["emails"] : 100;
    $api->tool_job_rebuild_threads((int) ($jobid), (int) ($threads), (int) ($emails));
}

if( isset( $options["fix-thread-crashes"] ) ) {    
    $api->fix_thread_crashes();
}

if( isset( $options["fix-job-unfinished"] ) ) {    
    $api->fix_job_unfinished();
}

if( isset( $options["status"] ) ) {    
    $api->status();
}

if( isset( $options["help"] ) ) {    
    $api->log("php cli.php --job-rebuild-threads --threads=15 --emails=200 --jobid=2356", "Rebuild Threads");
    $api->log("php cli.php --job-free-threads --jobid=2356", "Put all thread slots to available");
}

?>