<?php

// Terminal Colours:
define('TERM_DEFAULT', "\e[0m");
define('TERM_NORMAL', "\e[39m");
define('TERM_BOLD', "\e[1m");
define('TERM_UNDERLINED', "\e[4m");
define('TERM_RED', "\e[91m");
define('TERM_GREEN', "\e[32m");

define('PROCESS_START', array_sum(explode(' ', microtime())));

// Can be overriden in files
if (!defined('SECONDS_TO_EXPIRE')) {
    define('SECONDS_TO_EXPIRE', 3600); // assume one hour
}

if (is_file(LOCK_FILE) && file_get_contents(LOCK_FILE) > time()) {
    $time = date('Y-m-d H:i:s', file_get_contents(LOCK_FILE));
    echo TERM_RED . TERM_BOLD . "Lock exists, will expire at $time" . TERM_DEFAULT . PHP_EOL;
    exit();
}

file_put_contents(LOCK_FILE, time() + SECONDS_TO_EXPIRE);

function shutdownRemoveLock()
{
    @unlink(LOCK_FILE);

    // Mark as complete and note the time it took to complete.
    $time = array_sum(explode(' ', microtime()));
    echo PHP_EOL . TERM_GREEN . "Process completed in " . \Util::human_time_diff(PROCESS_START, $time, false , '') . TERM_DEFAULT . PHP_EOL;
}
register_shutdown_function('shutdownRemoveLock');