"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const get_stdin_1 = tslib_1.__importDefault(require("get-stdin"));
const debug_1 = require("../debug");
const bootstrap_1 = require("./bootstrap");
const command_1 = require("./command");
const create_rule_1 = require("./create-rule");
const init_1 = require("./init");
const search_1 = tslib_1.__importDefault(require("./search"));
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async () => {
    if (bootstrap_1.cli.flags.v) {
        bootstrap_1.cli.showVersion(); // And exit successfully.
    }
    if (bootstrap_1.cli.flags.h) {
        bootstrap_1.cli.showHelp(0); // And exit successfully.
    }
    if (bootstrap_1.cli.flags.verbose) {
        (0, debug_1.verbosely)();
    }
    if (bootstrap_1.cli.flags.init) {
        await (0, init_1.initialize)().catch(err => {
            process.stderr.write(err + '\n');
            process.exit(1);
        });
        return;
    }
    if (bootstrap_1.cli.flags.createRule) {
        await (0, create_rule_1.createRule)().catch(err => {
            process.stderr.write(err + '\n');
            process.exit(1);
        });
        return;
    }
    const files = bootstrap_1.cli.input;
    if (files.length) {
        if (bootstrap_1.cli.flags.search) {
            await (0, search_1.default)(files, bootstrap_1.cli.flags, bootstrap_1.cli.flags.search).catch(err => {
                process.stderr.write(err + '\n');
                process.exit(1);
            });
            return;
        }
        const hasError = await (0, command_1.command)(files, bootstrap_1.cli.flags).catch(err => {
            throw err;
            // process.exit(1);
        });
        process.exit(hasError ? 1 : 0);
    }
    if (usePipe()) {
        (0, get_stdin_1.default)()
            .then(async (stdin) => {
            if (stdin) {
                const hasError = await (0, command_1.command)([{ sourceCode: stdin }], {
                    ...bootstrap_1.cli.flags,
                    ignoreExt: true,
                }).catch(err => {
                    process.stderr.write(err + '\n');
                    process.exit(1);
                });
                process.exit(hasError ? 1 : 0);
            }
            // result is empty
            bootstrap_1.cli.showHelp(1);
        })
            .catch(reason => {
            // eslint-disable-next-line no-console
            console.warn(reason);
            process.exit(1);
        });
    }
    else {
        bootstrap_1.cli.showHelp(1);
    }
})();
function usePipe() {
    return !process.stdin.isTTY && process.stdout.isTTY;
}
