#!/usr/bin/apnscp_php -d opcache.enable_cli=1
<?php
define('INCLUDE_PATH',dirname(__DIR__));

if (file_exists(INCLUDE_PATH . '/lib/lservicelib.php')) {
	$ext = 'php';
	$ver = '';
} else {
	$ext = 'pht';
	$ver = PHP_VERSION_ID >= 80300 ? '' : '8';
}

include INCLUDE_PATH . "/lib/lservicelib{$ver}.{$ext}";
include INCLUDE_PATH . '/lib/apnscpfunction.php';
spl_autoload_register('apnscpFunctionInterceptor::autoload');

$optind = 0;
$opts = getopt('fd',['foreground','daemon'], $optind);
$argc = $_SERVER['argc'] - $optind;
$argv = array_slice($_SERVER['argv'], $optind);

while ($argc > 0) {
	$arg = array_pop($argv);
	switch ($arg) {
		case 'restart':
		case 'stop':
			if (!($pid = \Opcenter\Apnscp::pid())) {
				break;
			}
			posix_kill($pid, SIGTERM);
			usleep(5000);
			$i = 0;
			while (posix_kill($pid,0)) {
				usleep(50000);
				$i++;
				fwrite(STDERR, ".");
				if ($i > 50) {
					fwrite(STDERR,"Gave up waiting\n");
					posix_kill($pid, SIGKILL);
					break;
				}
			}
			if ('stop' == $arg) {
			    exit(0);
			}
	}
	$argc--;
}


$background = !getenv('DEBUG') || getenv('DEBUG') && (isset($opts['d']) || isset($opts['daemon']));
$foreground = isset($opts['f']) || isset($opts['foreground']) || (getenv('DEBUG') && !$background);
// clean path to the basics
$env = [
	'PATH' => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin'
];

if (getenv('PREFORK')) {
	$env['PREFORK'] = 1;
}

$env['NOTIFY_SOCKET'] = getenv('NOTIFY_SOCKET');
if ($hostname = (getenv('HOSTNAME') ?: gethostname())) {
	$env['HOSTNAME'] = $hostname;
}

if ($debug = getenv('DEBUG')) {
	$env['DEBUG'] = $debug;
}

if ($verbose = getenv('VERBOSE')) {
	$env['VERBOSE'] = $verbose;
}

$logPath = INCLUDE_PATH."/storage/logs/start.log";
if (file_exists($logPath)) {
	$fsize = posix_getrlimit()['soft filesize'] ?? 'unlimited';
	// 512 byte blocks, subtract boundary to ensure it's within the range
	if ($fsize !== 'unlimited' && ($fsize-511) <= filesize($logPath)) {
		$stat = stat($logPath);
		unlink($logPath) && touch($logPath) && chown($logPath, $stat['uid'])
			&& chgrp($logPath, $stat['gid']) && chmod($logPath, $stat['mode']);
		file_put_contents($logPath, "*** EMERGENCY TRUNCATION ***");
	}
}


if (\Opcenter\Apnscp::running()) {
	fwrite(STDERR, "Backend is already running with pid " . \Opcenter\Apnscp::pid());
}

if ($foreground) {
	pcntl_exec(PHP_BINARY,
		[INCLUDE_PATH. '/lib/lservice.php'],
		$env
	);
	exit(0);
}

$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("file", INCLUDE_PATH . "/storage/logs/start.log", "a"),
   2 => array("file", INCLUDE_PATH."/storage/logs/start.log", "a")
);
$pipes = [];

$process = proc_open(PHP_BINARY. ' ' . INCLUDE_PATH . '/lib/lservice.php',
	$descriptorspec,
	$pipes,
	__DIR__,
	$env
);
fclose($pipes[0]);
$status = proc_get_status($process);
\Opcenter\Apnscp::writeSystemd(["MAINPID=" . $status['pid'], "STATUS=Detaching"]);

exit($status['running'] ? 0 : $status['exitcode']);