<?php

namespace XcVm\Cli\CronJobs;

use XcVm\Cli\CommandInterface;
use XcVm\Cli\CronTrait;
use XcVm\Core\Config\ConfigReader;
use XcVm\Core\Config\SettingsManager;
use XcVm\Core\Logging\FileLogger;
use XcVm\Core\Updates\GitHubReleases;

/**
 * UpdateCronJob — update cron job
 *
 * @package XC_VM_CLI_CronJobs
 * @author  Divarion_D <https://github.com/Divarion-D>
 * @copyright 2025-2026 Vateron Media
 * @link    https://github.com/Vateron-Media/XC_VM
 * @license AGPL-3.0 https://www.gnu.org/licenses/agpl-3.0.html
 */

require_once __DIR__ . '/../CronTrait.php';

class UpdateCronJob implements CommandInterface {
    use CronTrait;

    public function getName(): string {
        return 'cron:update';
    }

    public function getDescription(): string {
        return 'Cron: check for \XC_VM updates';
    }

    public function execute(array $rArgs): int {
        if (!$this->assertRunAsXcVm()) {
            return 1;
        }

        if (!$this->isRunning()) {
            return 1;
        }

        global $db, $gitRelease;

        if (!$gitRelease) {
            if (defined('GIT_OWNER') && defined('GIT_REPO_MAIN')) {
                $gitRelease = new GitHubReleases(GIT_OWNER, GIT_REPO_MAIN, SettingsManager::getAll()['update_channel']);
            }
        }

        if (!$gitRelease) {
            FileLogger::log('cron', 'GitRelease service not initialized', 'cron:update');
            return 1;
        }

        if (!ConfigReader::get('is_lb')) {
            $rPort = (intval(explode(';', explode(' ', trim(explode('listen ', file_get_contents('/home/xc_vm/bin/nginx/conf/ports/http.conf'))[1]))[0])[0]) ?: 80);
        }

        $rUpdate = $gitRelease->getUpdate(XC_VM_VERSION);

        if (is_array($rUpdate) && $rUpdate['version'] && (0 < version_compare($rUpdate['version'], XC_VM_VERSION) || version_compare($rUpdate['version'], XC_VM_VERSION) == 0)) {
            echo 'Update is available!' . "\n";
            $updatedChanges = array();
            foreach (array_reverse($rUpdate['changelog']) as $rItem) {
                if (!($rItem['version'] == XC_VM_VERSION)) {
                    $updatedChanges[] = $rItem;
                } else {
                    break;
                }
            }
            $rUpdate['changelog'] = $updatedChanges;
            $db->query('UPDATE `settings` SET `update_data` = ?;', json_encode($rUpdate));
        } else {
            $db->query('UPDATE `settings` SET `update_data` = NULL;');
        }

        return 0;
    }

    private function isRunning(): bool {
        $rNginx = 0;
        exec('ps -fp $(pgrep -u xc_vm)', $rOutput, $rReturnVar);
        foreach ($rOutput as $rProcess) {
            $rSplit = explode(' ', preg_replace('!\\s+!', ' ', trim($rProcess)));
            if ($rSplit[8] == 'nginx:' && $rSplit[9] == 'master') {
                $rNginx++;
            }
        }
        return 0 < $rNginx;
    }
}
