#!/usr/bin/env node

const {ESLint} = require('eslint');

console.log(`Running ESLint version ${ESLint.version}...`);

const fs = require('fs');
const path = require('path');

function hasOption(...names) {
    return process.argv.some(arg => names.includes(arg));
}

function getOption(...names) {
    const optIndex =
        process.argv.findIndex(arg => names.includes(arg)) + 1;

    if (optIndex === 0)
        return undefined;

    return process.argv[optIndex];
}

(async function main() {
    const outputOption = getOption('--output-file', '-o');
    const outputPath = outputOption ? path.resolve(outputOption) : null;

    const sourceDir = path.dirname(process.argv[1]);
    process.chdir(path.resolve(sourceDir, '..'));

    const sources = ['js', 'subprojects/extensions-app/js', 'tests'];
    const eslint = new ESLint({cache: true});

    const results = await eslint.lintFiles(sources);
    const formatter = await eslint.loadFormatter(getOption('--format', '-f'));
    const resultText = formatter.format(results);

    if (outputPath) {
        fs.mkdirSync(path.dirname(outputPath), { recursive: true });
        fs.writeFileSync(outputPath, resultText);

        if (hasOption('--stdout')) {
            const consoleFormatter = await eslint.loadFormatter();
            console.log(consoleFormatter.format(results));
        }
    } else {
        console.log(resultText);
    }

    process.exitCode = results.some(r => r.errorCount > 0) ? 1 : 0;
})().catch((error) => {
    process.exitCode = 1;
    console.error(error);
});
