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

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

/**
 * Kwartz modification (debian/rules checks that it is present): Nextcloud runs with PHP 8.3.
 * The default "php" of the system can be another version (8.1 on Ubuntu 22.04), used by other applications.
 * When occ is started with another PHP version (for example "php occ" or "./occ"), occ starts again with php8.3 and the same arguments.
 * If php8.3 is not installed, occ stops with an error.
 */
const KWARTZ_PHP_VERSION = '8.3';
const KWARTZ_PHP_BINARY = '/usr/bin/php8.3';
if (PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION !== KWARTZ_PHP_VERSION) {
	if (!is_executable(KWARTZ_PHP_BINARY)) {
		fwrite(STDERR, 'occ requires PHP ' . KWARTZ_PHP_VERSION . ' but ' . KWARTZ_PHP_BINARY . ' is not installed (current PHP version: ' . PHP_VERSION . ')' . PHP_EOL);
		exit(1);
	}
	$kwartzArgs = array_merge([__FILE__], array_slice($_SERVER['argv'], 1));
	if (function_exists('pcntl_exec')) {
		// pcntl_exec replaces the current process: stdin, stdout, signals and the exit code stay the same.
		// pcntl_exec returns only if the execution failed.
		pcntl_exec(KWARTZ_PHP_BINARY, $kwartzArgs);
		fwrite(STDERR, 'occ: cannot execute ' . KWARTZ_PHP_BINARY . PHP_EOL);
		exit(1);
	}
	passthru(implode(' ', array_map('escapeshellarg', array_merge([KWARTZ_PHP_BINARY], $kwartzArgs))), $kwartzExitCode);
	exit($kwartzExitCode);
}

/**
 * Drop privileges when run as root
 */
function dropPrivileges(): void {
	if (posix_getuid() !== 0) {
		return;
	}

	$configPath = __DIR__ . '/config/config.php';
	$uid = @fileowner($configPath);
	if ($uid === false) {
		return;
	}
	$info = posix_getpwuid($uid);
	if ($info === false) {
		return;
	}
	posix_setuid($uid);
	posix_setgid($info['gid']);
}

dropPrivileges();
require_once __DIR__ . '/console.php';
