#!/usr/bin/php
<?php
// Some variables that might require tweaking on your system.
$public            = dirname(__DIR__).DIRECTORY_SEPARATOR.'public';
$php_cgi_bin       = '/Applications/php5/bin/php-cgi';
$nginx_bin         = 'nginx';
$nginx_host        = '127.0.0.1';
$nginx_port        = '8080';
$nginx_mime_types  = '/usr/local/etc/nginx/mime.types';
$fastcgi_params    = '/usr/local/etc/nginx/fastcgi_params';

if (count($argv) > 1 && in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
echo <<<"EOD"

Launch nginx for Respect/Rest development.

Usage:
$argv[0] <options>

    <options>
    -h, -?, --help, -help   Print this help message
    -d, --delete-temp       Delete the temp folder to regenerate config
    -p, --public <path>     Path to the public folder [$public]
    -c  --php-cgi <bin>     The fcgi php-cgi binary [$php_cgi_bin]
    -n  --nginx <bin>       The nginx binary [$nginx_bin]
    -h  --host <ip>         The ip nginx should use [$nginx_host]
    -i  --port <port>       The port nginx will listen on [$nginx_port]
    -m  --mime <conf>       Location of nginx mime types conf [$nginx_mime_types]
    -f  --fastcgi <conf>    Location of nginx fastcgi params conf [$fastcgi_params]


EOD;
exit(0);
}
$params = array(
        'p:' => 'public:','c:' => 'php-cgi:',
        'n:' => 'nginx:', 'h:' => 'host:', 'i:' => 'port:',
        'm:' => 'mime:', 'f:' => 'fastcgi:', 'd:' => 'delete-temp:',
        );

$opt = getopt(implode('',array_keys($params)),$params);
print_r($opt);
foreach ($opt as $key => $value) {
    switch ($key) {
        case 'd':
        case 'delete-temp':
            rmdir($tmp_dir);
            exit(0);
            break;
        case 'p':
        case 'public':
            $public = $value;
            break;
        case 'c':
        case 'php-cgi':
            $php_cgi_bin = $value;
            break;
        case 'n':
        case 'nginx':
            $nginx_bin = $value;
            break;
        case 'h':
        case 'host':
            $nginx_host = $value;
            break;
        case 'i':
        case 'port':
            $nginx_port = $value;
            break;
        case 'm':
        case 'mime':
            $nginx_mime_types = $value;
            break;
        case 'f':
        case 'fastcgi':
            $fastcgi_params = $value;
            break;
    }
}
$tmp_dir           = '/tmp/'.md5($public);
$fastcgi_bind_path = 'unix:'.$tmp_dir.'/php.socket';
# $fastcgi_bind_path = '127.0.0.1:9000'; // alternative bind path

$t = 0;
system($nginx_bin.' -v',$t);
if ($t != 0) {
    echo "Cant find nginx.\nPlease verify that nginx is installed".
         " and available on the PATH.\nExiting...\n";
    exit(1);
}

if (!is_dir($public)) {
   echo "Cannot find public folder: $public\n".
        "Please verify that the path exists.\nExiting...\n";
   exit(1);
}

if (!is_dir($tmp_dir)) {
    system('mkdir '.$tmp_dir, $t);
    if ($t != 0) {
        echo "Cannot create temporary folder: $tmp_dir\n".
             "Please verify that we have the appropriate privileges.\n".
             "Exiting...\n";
        exit(1);
    }
}

echo 'Configuring nginx for application in public folder: ', $public, PHP_EOL;

$conf = $tmp_dir.'/nginx.conf';

if (!is_file($conf))
    file_put_contents($conf, '
worker_processes  1;
error_log         /dev/stderr;
pid               '.$tmp_dir.'/nginx.pid;
events {
    worker_connections  1024;
}

http {
    include              '.$nginx_mime_types.';
    default_type         application/octet-stream;
    client_max_body_size 10m;
    sendfile             on;
    gzip                 on;
    keepalive_timeout    65;

    server {
        listen        '.$nginx_port.';
        server_name   '.$nginx_host.';
        server_tokens off;
        root          '.$public.';
        index         index.php index.html index.htm;

        access_log    /dev/stdout;

        location / {
                try_files $uri /index.php;
        }
        location ~ \.php$ {
                include      '.$fastcgi_params.';
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                fastcgi_pass '.$fastcgi_bind_path.';
        }
     }
}
');

system($nginx_bin.' -c '.$conf.' -t', $t);
if ($t != 0) {
    echo "Our configuration file was not acceptable to nginx.\n".
         "Please verify and repair the problem. ".
         "You can run the test with following command.\n".
         "$nginx_bin -c $conf -t\nExiting...\n";
    exit(1);
}

$bind = str_replace('unix:', '', $fastcgi_bind_path);
$php_process = proc_open($php_cgi_bin.' -b '.$bind,
                array(0 => STDIN, 1 => STDOUT, 2 => STDERR), $php_pipes);
if ($php_process === false)
    echo "\n\nWARNING! Failed to start php-cgi chances are that php won't work!!!\n";
else
    echo "Successfully started php-cgi bound to: $bind\n";

$process = proc_open($nginx_bin.' -c '.$conf,
                array(0 => STDIN, 1 => STDOUT, 2 => STDERR), $pipes);
if (is_resource($process)) {
    echo "nginx running at $nginx_host:$nginx_port from process:",
            posix_getpid(), PHP_EOL;

    echo PHP_EOL, 'Please enter stop to quit: ';
    while(trim(fgets(STDIN)) != 'stop') {
        echo 'Please enter stop to quit: ';
    }

    echo "\nShutting down nginx\n";
    system($nginx_bin.' -c '.$conf.' -s stop', $t);
    if ($t != 0)
         echo "Failed to stop nginx.\n".
               "Please verify if the process is still running.\n";

    echo "\nShutting down php-cgi (fcgi)\n";
    proc_terminate($php_process);
    $t = proc_close($php_process); echo $t;
    if ($t == 0)
         echo "PHP process closed successfully.\n";
    else
         echo "Failed to close the PHP process.\n".
              "Please verify that no orphan processes are still running,\n";


    proc_terminate($process);
    $t = proc_close($process);
    if ($t == 0)
         echo "Process closed successfully.\n\nThank you!\nGood bye.\n\n";
    else
         echo "Failed to close the process.\n".
              "Please verify that no orphan processes are still running,\n".
              "\nGood bye.\n\n";
    exit($t);
}
echo "Process did not start.\nPlease verify log files to see if you can find out what went wrong.";
exit(1);
