#!/usr/bin/php -q
<?php

// Debug Mode for IDE runtime debugger
define("SCRIPTDEBUG", 0);

// change to web server root to load scripts
chdir("/var/www");
/** @noinspection PhpIncludeInspection */
require_once "public/config.inc.php";

function writeError($id, $msg) {
    fwrite($GLOBALS['stderr'], "ERROR: (" . $id . ") " . $msg . "\n");
}

function writeUsage() {
    fwrite($GLOBALS['stdout'], "Usage: " . $GLOBALS['argv'][0] . "\n");
}

// Get a file's contents, or default to second param
function _getContents($file, $default = '') {
    return !is_file($file) || !is_readable($file) || !($contents = @file_get_contents($file)) ? $default : trim($contents);
}

function gotcha() {
    try {
        $pid = _getContents('/var/run/watchdog.pid', false);
        if ($pid != false && is_numeric($pid)) {
            $opts = array('http' => array('timeout' => 7));
            $context = stream_context_create($opts);
            $response = @file_get_contents('http://localhost/cgi-bin/watchdog.cgi?cmd=StartQueueCheck', false, $context);
        } else {
            $response = 'No watchdog running';
        }
        $needle = 'No error';

        $pos = strpos($response, $needle);
        if ($pos === false) {
            writeError(3, "Error trigger: " . $response);
            exit(3);
        }
    } catch (Exception $e) {
        writeError(1, "General Error: " . $e->getMessage());
        exit(1);
    }
}

function main($argc, /** @noinspection PhpUnusedParameterInspection */
              $argv) {
    if (SCRIPTDEBUG) {
        gotcha();
        exit(0);
    } else {
        if ($argc > 1) {
            writeUsage();
            writeError(2, "Wrong or missing command line parameters");
            exit(2);
        }
        gotcha();
        exit(0);
    }
}

// supported STDIN/OUT/ERR syntax for php version 4.3 till 5.3
$stderr = fopen('php://stderr', 'w');
$stdout = fopen('php://stdout', 'w');
// $argc, $argv are filled in by the CLI engine and defined as globals
main($argc, $argv);
