<?php

/**
 * todo
 */
class test{
    /**
     * todo
     */
    function newconn($request){

        $method = $request->getMethod();
        $path   = $request->getUri()->getPath();
        $type = "text/plain";
        global $_GET;
        parse_str($request->getUri()->getQuery(), $_GET);
        print_r($_GET);

        // --- einfache Routing-Logik ---
        if (str_ends_with($path,'/ping')) {
            $body = "pong\n";
            $status = 200;
        } elseif (str_ends_with($path,'/info')) {
            $body = json_encode([
                'pid'    => getmypid(),
                'method' => $method,
                'path'   => $path,
                'this_is_from_test' => 'yes'
            ], JSON_PRETTY_PRINT);
            $status = 200;
        } elseif (str_ends_with($path,'/phpinfo')) {
            ob_start();
            phpinfo();
            $body = ob_get_contents();
            ob_end_clean();
            $status=200;
            $type="text/html";
        } elseif ($path === '/diffget' || $path === '/diffget_server.php' || $path === '/diffget/diffget_server.php') {
            $status=200;
            ob_start();
            try {
                pw_diffget_server::main(true);
            }
            catch(Throwable $e) {
                print_r($e);
                $status=500;
            }
            $body = ob_get_contents();
            ob_end_clean();
        } elseif (str_ends_with($path,'/requestinfo')) {
            ob_start();
            print_r($request);
            $body = ob_get_contents();
            ob_end_clean();
            $status=200;
        } else {
            $body = "not found\n";
            $status = 404;
        }

        // --- Response bauen ---
        $response = new GuzzleHttp\Psr7\Response(
            $status,
            [
                'Content-Type' => $type.'; charset=utf-8',
                'Content-Length' => strlen($body),
                'Connection' => 'close',
            ],
            $body
        );
        return($response);
    }
}









if(isset($argv[1]) && $argv[1]=="daemon"){
    main_daemon();
    exit(0);
}
elseif(isset($argv[1]) && $argv[1]=="process"){
    main_do();
    exit(0);
}
else{
    echo "Usage: diffget_server daemon|process\r\n";
    exit(1);
}

function main_daemon(){
    global $logger_fp;
    while(true){
        // Do it endless
        $logger_fp = fopen("/var/log/diffget_server.log","a");
        ob_start("callback_pass_str",20);
        passthru("diffget_server process 2>&1");
        ob_end_flush();
        fclose($logger_fp);
        sleep(60);
    }
}
function callback_pass_str($buffer){
    global $logger_fp;
    fwrite($logger_fp,$buffer);
    return($buffer);
}

function main_do(){
    ini_set('memory_limit', '2048M');
    echo date("d.m.Y H:i:s")." starting...\r\n";
    $test = new test;
    pwews_master::main($test,8091);
    echo date("d.m.Y H:i:s")."ended!\r\n";
}



