#!/usr/bin/env php
<?php

$autoload = realpath(__DIR__ . "/../vendor/autoload.php");
if (!file_exists($autoload))
{
    $autoload = realpath(__DIR__ . "/../../../autoload.php");
    if (!file_exists($autoload))
    {
        throw new \Exception('Autoload not found. Did you run `composer dump-autload`?');
    }
}
require_once($autoload);

echo "\nPHP Daemonize class @ 2015\n";

if ($argc < 2)
{
    showUsage();
}

$action = $argv[1];

try
{
    switch ($action)
    {
        case "install":
            if ($argc < 5)
            {
                throw new Exception('All parameters are required');
            }
            $serviceName = $argv[2];
            $className = $argv[3];
            $bootstrap = isset($argv[4]) ? $argv[4] : "";
            $description = isset($argv[5]) ? $argv[5] : "Daemon for PHP Class $className";
            $template = __DIR__ . "/../template/linux-initd-service.conf";
            ByJG\Daemon\Daemonize::install($serviceName, $className, $bootstrap, $template, $description);
            break;

        case "uninstall":
            $serviceName = $argv[2];
            shell_exec("service $serviceName stop");
            ByJG\Daemon\Daemonize::uninstall($serviceName);
            break;

        case "list":
            $list = ByJG\Daemon\Daemonize::listServices();

            if (count($list) == 0)
            {
                echo "\nThere is no daemonize services installed.\n";
            }
            else
            {
                echo "\nList of daemonize services: \n";
                foreach ($list as $filename)
                {
                    echo " - " . basename($filename) . "\n";
                }
            }
            break;

        case "run":
            $className = $argv[2];
            $bootstrap = $argv[3];
            require_once $bootstrap;
            $runner = new \ByJG\Daemon\Runner($className, array_slice($argv, 4), false);
            $runner->execute();
            break;

        default:
            throw new \Exception("Invalid action");
    }
}
catch (Exception $ex)
{
    echo "\nError: " . $ex->getMessage() . "\n";
    showUsage();
}

echo "\nDone.\n\n";

function showUsage()
{
    echo "\nUsage:\n";
    echo "    daemonize install service_name classname bootstrap 'description'\n";
    echo "    daemonize run classname bootstrap\n";
    echo "    daemonize list\n";
    echo "    daemonize uninstall service_name \n";
    echo "\n";
    echo "Where:\n";
    echo "    service_name is the unix service name\n";
    echo "    service_name is the PHP class and method like ClassName::Method\n";
    echo "    bootstrap is the full path to a PHP file that load all requirements (like vendor/autoload.php) \n";
    echo "    descriptions is an optional service description \n";
    echo "\n";
    die();
}
