"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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
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 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'));
}
function runCommand(command) {
    return __awaiter(this, void 0, void 0, function* () {
        const goCommand = yield (0, promise_utils_1.go)(command);
        if (!goCommand.success) {
            airnode_utilities_1.logger.log('\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',
    'remove-with-receipt -r config/receipt.json',
    'remove-with-deployment-details --airnode-address 0x6abEdc0A4d1A79eD62160396456c95C5607369D3 --stage dev --cloud-provider aws --region us-east-1',
];
drawHeader();
(0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
    .option('debug', {
    description: 'Run in debug mode',
    default: false,
    type: 'boolean',
})
    .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',
    },
}, (args) => __awaiter(void 0, void 0, void 0, function* () {
    logger.debugMode(args.debug);
    logger.debug(`Running command ${args._[0]} with arguments ${(0, cli_1.longArguments)(args)}`);
    yield 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',
    },
}, (args) => __awaiter(void 0, void 0, void 0, function* () {
    logger.debugMode(args.debug);
    logger.debug(`Running command ${args._[0]} with arguments ${(0, cli_1.longArguments)(args)}`);
    yield runCommand(() => (0, commands_1.removeWithReceipt)(args.receipt));
    return;
}))
    .command('remove-with-deployment-details', 'Removes a deployed Airnode instance using the Airnode short address and cloud provider specifications', {
    'airnode-address': {
        alias: 'a',
        description: 'Airnode Address',
        type: 'string',
        demandOption: true,
    },
    stage: {
        alias: 's',
        description: 'Stage (environment)',
        type: 'string',
        demandOption: true,
    },
    'cloud-provider': {
        alias: 'c',
        description: 'Cloud provider',
        choices: ['aws', 'gcp'],
        demandOption: true,
    },
    region: {
        alias: 'e',
        description: 'Region',
        type: 'string',
        demandOption: true,
    },
    'project-id': {
        alias: 'p',
        description: 'Project ID (required for GCP only)',
        type: 'string',
    },
}, (args) => __awaiter(void 0, void 0, void 0, function* () {
    logger.debugMode(args.debug);
    logger.debug(`Running command ${args._[0]} with arguments ${(0, cli_1.longArguments)(args)}`);
    if (args['cloud-provider'] === 'gcp') {
        if (!args['project-id']) {
            // Throwing strings to prevent yargs from showing error stack trace
            throw `Missing required argument '--project-id' for removing a GCP deployment`;
        }
    }
    yield runCommand(() => (0, infrastructure_2.removeAirnode)(args['airnode-address'], args.stage, {
        type: args['cloud-provider'],
        region: args.region,
        projectId: args['project-id'],
    }));
    return;
}))
    .example(cliExamples.map((line) => [`$0 ${line}\n`]))
    .help()
    .demandCommand(1)
    .strict()
    .wrap(120).argv;
//# sourceMappingURL=index.js.map