"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const yargs_1 = __importDefault(require("yargs"));
const helpers_1 = require("yargs/helpers");
const uniq_1 = __importDefault(require("lodash/uniq"));
const sortBy_1 = __importDefault(require("lodash/sortBy"));
const airnode_node_1 = require("@api3/airnode-node");
const airnode_utilities_1 = require("@api3/airnode-utilities");
const promise_utils_1 = require("@api3/promise-utils");
const commands_1 = require("./commands");
const logger = __importStar(require("../utils/logger"));
const cli_1 = require("../utils/cli");
const infrastructure_1 = require("../utils/infrastructure");
const infrastructure_2 = require("../infrastructure");
function drawHeader() {
    airnode_utilities_1.logger.log([
        '  ___  _                      _      ',
        ' / _ \\(_)                    | |     ',
        '/ /_\\ \\_ _ __ _ __   ___   __| | ___ ',
        "|  _  | | '__| '_ \\ / _ \\ / _` |/ _ \\",
        '| | | | | |  | | | | (_) | (_| |  __/',
        '\\_| |_/_|_|  |_| |_|\\___/ \\__,_|\\___|',
        '',
        `          Airnode v${(0, airnode_node_1.version)()}`,
        '',
    ].join('\n'));
}
async function runCommand(command) {
    const goCommand = await (0, promise_utils_1.go)(command);
    if (!goCommand.success) {
        logger.consoleLog('\n\n\nError details:');
        // Logging an error here likely results in excessive logging since the errors are usually logged at the place where they
        // happen. However if we do not log the error here we risk having unhandled silent errors. The risk is not worth it.
        if (goCommand.error instanceof infrastructure_1.MultiMessageError) {
            goCommand.error.messages.forEach((m) => logger.fail(m));
        }
        else {
            logger.fail(goCommand.error.message);
        }
        // eslint-disable-next-line functional/immutable-data
        process.exitCode = 1;
    }
}
const cliExamples = [
    'deploy -c config/config.json -s config/secrets.env -r config/receipt.json -l config/logs/',
    'list --cloud-providers gcp',
    'info aws808e2a22',
    'fetch-files aws808e2a22',
    'rollback aws808e2a22 5bbcd317',
    'remove-with-receipt -r config/receipt.json',
    'remove aws808e2a22',
];
(0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
    .option('debug', {
    description: 'Run in debug mode',
    default: false,
    type: 'boolean',
})
    .option('logs', {
    alias: 'l',
    description: 'Output path for log files',
    default: 'config/logs/',
    type: 'string',
})
    .command('deploy', 'Executes Airnode deployments specified in the config file', {
    configuration: {
        alias: ['c', 'config', 'conf'],
        description: 'Path to configuration file',
        default: 'config/config.json',
        type: 'string',
    },
    secrets: {
        alias: 's',
        description: 'Path to secrets file',
        default: 'config/secrets.env',
        type: 'string',
    },
    receipt: {
        alias: 'r',
        description: 'Output path for receipt file',
        default: 'config/receipt.json',
        type: 'string',
    },
    // Flag arguments without value are not supported. See: https://github.com/yargs/yargs/issues/1532
    'auto-remove': {
        description: 'Enable automatic removal of deployed resources for failed deployments',
        default: true,
        type: 'boolean',
    },
}, async (args) => {
    drawHeader();
    logger.debugMode(args.debug);
    logger.setLogsDirectory(args.logs);
    logger.debug(`Running command ${args._[0]} with arguments ${(0, cli_1.longArguments)(args)}`);
    await runCommand(() => (0, commands_1.deploy)(args.configuration, args.secrets, args.receipt, args['auto-remove']));
})
    .command('remove-with-receipt', 'Removes a deployed Airnode instance using a receipt file', {
    receipt: {
        alias: 'r',
        description: 'Path to receipt file',
        default: 'config/receipt.json',
        type: 'string',
    },
}, async (args) => {
    drawHeader();
    logger.debugMode(args.debug);
    logger.setLogsDirectory(args.logs);
    logger.debug(`Running command ${args._[0]} with arguments ${(0, cli_1.longArguments)(args)}`);
    await runCommand(() => (0, commands_1.removeWithReceipt)(args.receipt));
    return;
})
    .command('remove <deployment-id>', 'Removes a deployed Airnode instance', (yargs) => {
    yargs.positional('deployment-id', {
        description: `ID of the deployment to remove (from 'list' command)`,
        type: 'string',
    });
}, async (args) => {
    drawHeader();
    logger.debugMode(args.debug);
    logger.setLogsDirectory(args.logs);
    logger.debug(`Running command ${args._[0]} with arguments ${(0, cli_1.longArguments)(args)}`);
    await runCommand(() => 
    // Looks like due to the bug in yargs (https://github.com/yargs/yargs/issues/1649) we need to specify the type explicitely
    (0, infrastructure_2.removeAirnode)(args.deploymentId));
    return;
})
    .command('list', 'Lists deployed Airnode instances', {
    'cloud-providers': {
        alias: 'c',
        description: 'Cloud providers to list Airnodes from',
        default: airnode_node_1.availableCloudProviders,
        choices: airnode_node_1.availableCloudProviders,
        type: 'array',
        coerce: (option) => (0, sortBy_1.default)((0, uniq_1.default)(option)),
    },
}, async (args) => {
    logger.debugMode(args.debug);
    logger.setLogsDirectory(args.logs);
    logger.debug(`Running command ${args._[0]} with arguments ${(0, cli_1.longArguments)(args)}`);
    await (0, infrastructure_2.listAirnodes)(args.cloudProviders);
})
    .command('info <deployment-id>', 'Displays info about deployed Airnode', (yargs) => {
    yargs.positional('deployment-id', {
        description: `ID of the deployment to show info for (from 'list' command)`,
        type: 'string',
    });
}, async (args) => {
    logger.debugMode(args.debug);
    logger.setLogsDirectory(args.logs);
    logger.debug(`Running command ${args._[0]} with arguments ${(0, cli_1.longArguments)(args)}`);
    // Looks like due to the bug in yargs (https://github.com/yargs/yargs/issues/1649) we need to specify the type explicitely
    const goDeploymentInfo = await (0, promise_utils_1.go)(() => (0, infrastructure_2.deploymentInfo)(args.deploymentId));
    if (!goDeploymentInfo.success) {
        logger.fail(goDeploymentInfo.error.message);
        // eslint-disable-next-line functional/immutable-data
        process.exitCode = 1;
    }
})
    .command('fetch-files <deployment-id> [version-id]', 'Fetch deployment files for the deployed Airnode', (yargs) => {
    yargs.positional('deployment-id', {
        description: `ID of the deployment to fetch files for (from 'list' command)`,
        type: 'string',
    });
    yargs.positional('version-id', {
        description: `ID of the deployment version to fetch files for (from 'info' command)`,
        type: 'string',
    });
    yargs.option('output-dir', {
        alias: 'o',
        description: 'Where to store fetched files',
        default: 'config/',
        type: 'string',
    });
}, async (args) => {
    logger.debugMode(args.debug);
    logger.setLogsDirectory(args.logs);
    logger.debug(`Running command ${args._[0]} with arguments ${(0, cli_1.longArguments)(args)}`);
    // Looks like due to the bug in yargs (https://github.com/yargs/yargs/issues/1649) we need to specify the types explicitely
    const goFetchFiles = await (0, promise_utils_1.go)(() => (0, infrastructure_2.fetchFiles)(args.deploymentId, args.outputDir, args.versionId));
    if (!goFetchFiles.success) {
        logger.fail(goFetchFiles.error.message);
        // eslint-disable-next-line functional/immutable-data
        process.exitCode = 1;
    }
})
    .command('rollback <deployment-id> <version-id>', 'Deploy one of the previous Airnode deployment versions', (yargs) => {
    yargs.positional('deployment-id', {
        description: `ID of the deployment to rollback (from 'list' command)`,
        type: 'string',
    });
    yargs.positional('version-id', {
        description: `ID of the deployment version to rollback to (from 'info' command)`,
        type: 'string',
    });
    yargs.option('receipt', {
        alias: 'r',
        description: 'Output path for receipt file',
        default: 'config/receipt.json',
        type: 'string',
    });
    // Flag arguments without value are not supported. See: https://github.com/yargs/yargs/issues/1532
    yargs.option('auto-remove', {
        description: 'Enable automatic removal of deployed resources for failed deployments',
        default: true,
        type: 'boolean',
    });
}, async (args) => {
    logger.debugMode(args.debug);
    logger.debug(`Running command ${args._[0]} with arguments ${(0, cli_1.longArguments)(args)}`);
    // Looks like due to the bug in yargs (https://github.com/yargs/yargs/issues/1649) we need to specify the types explicitely
    const goRollback = await (0, promise_utils_1.go)(() => (0, commands_1.rollback)(args.deploymentId, args.versionId, args.receipt, args.autoRemove));
    if (!goRollback.success) {
        logger.fail(goRollback.error.message);
        // eslint-disable-next-line functional/immutable-data
        process.exitCode = 1;
    }
})
    .example(cliExamples.map((line) => [`$0 ${line}\n`]))
    .help()
    .demandCommand(1)
    .strict()
    .wrap(120).argv;
//# sourceMappingURL=index.js.map