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

declare(strict_types=1);

include $_composer_autoload_path ?? __DIR__ . '/../vendor/autoload.php';

use LsifPhp\Git\Git;
use LsifPhp\Indexer\Indexer;
use LsifPhp\Protocol\Emitter;
use LsifPhp\Protocol\ToolInfo;

$options = \getopt('h', ['help', 'memory-limit:']);
if ($options === false) {
    echo "Cannot parse options.\n";
    exit(1);
}

if (isset($options['h']) || isset($options['help'])) {
    echo "usage: {$argv[0]} [options]\n\n";
    echo "lsif-php is an LSIF indexer for PHP\n\n";
    echo "Options:\n";
    echo "  -h --help               display this help and exit\n";
    echo "     --memory-limit=\"1G\"  memory limit\n";
    exit(0);
}

$memoryLimit = $options['memory-limit'] ?? '1G';
if (!\is_string($memoryLimit)) {
    echo "Invalid memory limit.\n";
    exit(1);
}

if (\ini_set('memory_limit', $memoryLimit) === false) {
    echo "Cannot set memory limit {$memoryLimit}.\n";
    exit(1);
}

$projectRoot = \getcwd();
$toolInfo = new ToolInfo('lsif-php', '0.0.5', \array_splice($argv, 1));

$git = new Git();
$emitter = new Emitter();
$indexer = new Indexer($projectRoot, $emitter, $toolInfo, $git->version());
$indexer->index();
$emitter->write();
