<?php
require_once(dirname(__FILE__) . '/../common.inc.php');

$raw = file_get_contents('php://input');
if ($raw !== false && $raw !== '') {
    $json = json_decode($raw, true);
    if (is_array($json) && isset($json['nsp'])) {
        $_REQUEST['nsp'] = $json['nsp'];
        $_POST['nsp']    = $json['nsp'];
    }
}

pre_init();
init_session();
grab_request_vars();
check_authentication(false);
is_admin_with_error_message();
check_nagios_session_protector();

header('Content-Type: application/json');

$helperDir  = '/usr/local/nagiosxi/var/nagios/xihelper';
$log        = $helperDir . '/install.log';
$script     = __DIR__ . '/install.sh';
$statusFile = $helperDir . '/xihelper.install.status';

if (file_exists($statusFile)) {
    $status = trim(file_get_contents($statusFile));

    if ($status === 'running') {
        echo json_encode([
            'success' => false,
            'error'   => 'Installation is already running'
        ]);
        exit;
    }

    if ($status === 'success') {
        echo json_encode([
            'success' => false,
            'error'   => 'Dependencies are already installed'
        ]);
        exit;
    }

    if ($status === 'error') {
        unlink($statusFile);
    }
}

$cmd = sprintf('sudo %s > /dev/null 2>&1 &', escapeshellarg($script));
exec($cmd);

echo json_encode([
    'success' => true,
    'message' => 'Installation started',
    'log'     => $log
]);
?>