"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeAirnode = exports.deployAirnode = void 0;
var fs = __importStar(require("fs"));
var os = __importStar(require("os"));
var util = __importStar(require("util"));
var child = __importStar(require("child_process"));
var path = __importStar(require("path"));
var compact_1 = __importDefault(require("lodash/compact"));
var isEmpty_1 = __importDefault(require("lodash/isEmpty"));
var omitBy_1 = __importDefault(require("lodash/omitBy"));
var isNil_1 = __importDefault(require("lodash/isNil"));
var aws = __importStar(require("./aws"));
var gcp = __importStar(require("./gcp"));
var logger = __importStar(require("../utils/logger"));
var infrastructure_1 = require("../utils/infrastructure");
var exec = util.promisify(child.exec);
// TODO:
// Pass handler as argument
var handlerDir = path.resolve("".concat(__dirname, "/../../.webpack"));
var terraformDir = path.resolve("".concat(__dirname, "/../../terraform"));
var terraformStateDir = "".concat(terraformDir, "/state");
var terraformAirnodeDir = "".concat(terraformDir, "/airnode");
var spinner;
function runCommand(command, options) {
    return __awaiter(this, void 0, void 0, function () {
        var stringifiedOptions, commandSpinner, stdout, err_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    stringifiedOptions = JSON.stringify(options);
                    commandSpinner = logger.debugSpinner("Running command '".concat(command, "' with options ").concat(stringifiedOptions));
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, exec(command, options)];
                case 2:
                    stdout = (_a.sent()).stdout;
                    commandSpinner.succeed("Finished command '".concat(command, "' with options ").concat(stringifiedOptions));
                    return [2 /*return*/, stdout];
                case 3:
                    err_1 = _a.sent();
                    if (options.ignoreError) {
                        if (logger.inDebugMode()) {
                            spinner.info();
                            logger.warn("Warning: ".concat(err_1.message));
                        }
                        commandSpinner.warn("Command '".concat(command, "' with options ").concat(stringifiedOptions, " failed"));
                        return [2 /*return*/, ''];
                    }
                    spinner.info();
                    logger.fail(err_1.toString());
                    commandSpinner.fail("Command '".concat(command, "' with options ").concat(stringifiedOptions, " failed"));
                    throw new Error("Command failed: ".concat(err_1.cmd));
                case 4: return [2 /*return*/];
            }
        });
    });
}
function execTerraform(execOptions, command, args, options) {
    return __awaiter(this, void 0, void 0, function () {
        var formattedArgs, fullCommand;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    formattedArgs = (0, infrastructure_1.formatTerraformArguments)(args);
                    fullCommand = (0, compact_1.default)(['terraform', command, formattedArgs.join(' '), options === null || options === void 0 ? void 0 : options.join(' ')]).join(' ');
                    return [4 /*yield*/, runCommand(fullCommand, execOptions)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    });
}
function awsApplyArguments(cloudProvider) {
    return [['var', 'aws_region', cloudProvider.region]];
}
function gcpApplyArguments(cloudProvider) {
    return [
        ['var', 'gcp_region', cloudProvider.region],
        ['var', 'gcp_project', cloudProvider.projectId],
    ];
}
function awsAirnodeInitArguments(cloudProvider, bucket) {
    return [
        ['backend-config', 'region', cloudProvider.region],
        ['backend-config', 'bucket', bucket],
    ];
}
function gcpAirnodeInitArguments(_cloudProvider, bucket) {
    return [['backend-config', 'bucket', bucket]];
}
function awsAirnodeImportOptions(_cloudProvider) {
    return [];
}
function gcpAirnodeImportOptions(cloudProvider) {
    return ['module.startCoordinator.google_app_engine_application.app[0]', cloudProvider.projectId];
}
var cloudProviderLib = {
    aws: aws,
    gcp: gcp,
};
var cloudProviderAirnodeManageArguments = {
    aws: awsApplyArguments,
    gcp: gcpApplyArguments,
};
var cloudProviderAirnodeInitArguments = {
    aws: awsAirnodeInitArguments,
    gcp: gcpAirnodeInitArguments,
};
var cloudProviderAirnodeImportOptions = {
    aws: awsAirnodeImportOptions,
    gcp: gcpAirnodeImportOptions,
};
function prepareAirnodeInitArguments(cloudProvider, bucket, commonArguments) {
    return __spreadArray(__spreadArray([], __read(cloudProviderAirnodeInitArguments[cloudProvider.type](cloudProvider, bucket)), false), __read(commonArguments), false);
}
function prepareAirnodeManageArguments(cloudProvider, commonArguments) {
    return __spreadArray(__spreadArray([], __read(cloudProviderAirnodeManageArguments[cloudProvider.type](cloudProvider)), false), __read(commonArguments), false);
}
function getBucketName(airnodeAddressShort, stage) {
    return "airnode-".concat(airnodeAddressShort, "-").concat(stage, "-terraform").toLowerCase();
}
function terraformAirnodeManage(command, execOptions, cloudProvider, bucket, variables) {
    return __awaiter(this, void 0, void 0, function () {
        var terraformAirnodeCloudProviderDir, airnodeAddressShort, stage, configPath, secretsPath, httpGateway, httpSignedDataGateway, commonArguments, importOptions;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    terraformAirnodeCloudProviderDir = path.join(terraformAirnodeDir, cloudProvider.type);
                    airnodeAddressShort = variables.airnodeAddressShort, stage = variables.stage, configPath = variables.configPath, secretsPath = variables.secretsPath, httpGateway = variables.httpGateway, httpSignedDataGateway = variables.httpSignedDataGateway;
                    commonArguments = [['from-module', terraformAirnodeCloudProviderDir]];
                    return [4 /*yield*/, execTerraform(execOptions, 'init', prepareAirnodeInitArguments(cloudProvider, bucket, commonArguments))];
                case 1:
                    _a.sent();
                    commonArguments = [
                        ['var', 'airnode_address_short', airnodeAddressShort],
                        ['var', 'stage', stage],
                        ['var', 'configuration_file', configPath ? path.resolve(configPath) : 'NULL'],
                        ['var', 'secrets_file', secretsPath ? path.resolve(secretsPath) : 'NULL'],
                        ['var', 'handler_dir', handlerDir],
                        ['var', 'disable_concurrency_reservation', "".concat(!!cloudProvider.disableConcurrencyReservations)],
                        ['input', 'false'],
                        'no-color',
                    ];
                    // In case of Airnode removal the concurrency information is not available so can't be passed as a variable
                    if (cloudProvider.maxConcurrency) {
                        commonArguments.push(['var', 'max_concurrency', "".concat(cloudProvider.maxConcurrency)]);
                    }
                    if (httpGateway === null || httpGateway === void 0 ? void 0 : httpGateway.enabled) {
                        commonArguments.push(['var', 'http_api_key', httpGateway.apiKey]);
                        if (httpGateway.maxConcurrency) {
                            commonArguments.push(['var', 'http_max_concurrency', "".concat(httpGateway.maxConcurrency)]);
                        }
                    }
                    if (httpSignedDataGateway === null || httpSignedDataGateway === void 0 ? void 0 : httpSignedDataGateway.enabled) {
                        commonArguments.push(['var', 'http_signed_data_api_key', httpSignedDataGateway.apiKey]);
                        if (httpSignedDataGateway.maxConcurrency) {
                            commonArguments.push(['var', 'http_signed_data_max_concurrency', "".concat(httpSignedDataGateway.maxConcurrency)]);
                        }
                    }
                    if (!(command === 'apply')) return [3 /*break*/, 3];
                    importOptions = cloudProviderAirnodeImportOptions[cloudProvider.type](cloudProvider);
                    if (!!(0, isEmpty_1.default)(importOptions)) return [3 /*break*/, 3];
                    return [4 /*yield*/, execTerraform(__assign(__assign({}, execOptions), { ignoreError: true }), 'import', prepareAirnodeManageArguments(cloudProvider, commonArguments), cloudProviderAirnodeImportOptions[cloudProvider.type](cloudProvider))];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    commonArguments.push('auto-approve');
                    return [4 /*yield*/, execTerraform(execOptions, command, prepareAirnodeManageArguments(cloudProvider, commonArguments))];
                case 4:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function deployAirnode(params) {
    return __awaiter(this, void 0, void 0, function () {
        var airnodeAddressShort, stage, cloudProvider, type, region, output, err_2;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    airnodeAddressShort = params.airnodeAddressShort, stage = params.stage, cloudProvider = params.cloudProvider;
                    type = cloudProvider.type, region = cloudProvider.region;
                    spinner = logger.spinner("Deploying Airnode ".concat(airnodeAddressShort, " ").concat(stage, " to ").concat(type, " ").concat(region));
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, deploy(params)];
                case 2:
                    output = _a.sent();
                    spinner.succeed("Deployed Airnode ".concat(airnodeAddressShort, " ").concat(stage, " to ").concat(type, " ").concat(region));
                    return [2 /*return*/, output];
                case 3:
                    err_2 = _a.sent();
                    spinner.fail("Failed deploying Airnode ".concat(airnodeAddressShort, " ").concat(stage, " to ").concat(type, " ").concat(region));
                    throw err_2;
                case 4: return [2 /*return*/];
            }
        });
    });
}
exports.deployAirnode = deployAirnode;
function transformTerraformOutput(terraformOutput) {
    var _a, _b;
    var parsedOutput = JSON.parse(terraformOutput);
    return (0, omitBy_1.default)({
        httpGatewayUrl: (_a = parsedOutput.http_gateway_url) === null || _a === void 0 ? void 0 : _a.value,
        httpSignedDataGatewayUrl: (_b = parsedOutput.http_signed_data_gateway_url) === null || _b === void 0 ? void 0 : _b.value,
    }, isNil_1.default);
}
function deploy(_a) {
    var airnodeAddressShort = _a.airnodeAddressShort, stage = _a.stage, cloudProvider = _a.cloudProvider, httpGateway = _a.httpGateway, httpSignedDataGateway = _a.httpSignedDataGateway, configPath = _a.configPath, secretsPath = _a.secretsPath;
    return __awaiter(this, void 0, void 0, function () {
        var cloudProviderType, bucket, terraformStateCloudProviderDir, stateTmpDir, execOptions_1, commonArguments, airnodeTmpDir, execOptions, output;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (logger.inDebugMode()) {
                        spinner.info();
                    }
                    cloudProviderType = cloudProvider.type;
                    bucket = getBucketName(airnodeAddressShort, stage);
                    terraformStateCloudProviderDir = path.join(terraformStateDir, cloudProviderType);
                    return [4 /*yield*/, cloudProviderLib[cloudProviderType].stateExists(bucket, cloudProvider)];
                case 1:
                    if (!!(_b.sent())) return [3 /*break*/, 4];
                    // Run state recipes
                    logger.debug('Running state Terraform recipes');
                    stateTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'airnode'));
                    execOptions_1 = { cwd: stateTmpDir };
                    return [4 /*yield*/, execTerraform(execOptions_1, 'init', [['from-module', terraformStateCloudProviderDir]])];
                case 2:
                    _b.sent();
                    commonArguments = [
                        ['var', 'airnode_address_short', airnodeAddressShort],
                        ['var', 'stage', stage],
                        ['input', 'false'],
                        'no-color',
                        'auto-approve',
                    ];
                    return [4 /*yield*/, execTerraform(execOptions_1, 'apply', prepareAirnodeManageArguments(cloudProvider, commonArguments))];
                case 3:
                    _b.sent();
                    _b.label = 4;
                case 4:
                    // Run airnode recipes
                    logger.debug('Running Airnode Terraform recipes');
                    airnodeTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'airnode'));
                    execOptions = { cwd: airnodeTmpDir };
                    return [4 /*yield*/, terraformAirnodeManage('apply', execOptions, cloudProvider, bucket, {
                            airnodeAddressShort: airnodeAddressShort,
                            stage: stage,
                            configPath: configPath,
                            secretsPath: secretsPath,
                            httpGateway: httpGateway,
                            httpSignedDataGateway: httpSignedDataGateway,
                        })];
                case 5:
                    _b.sent();
                    return [4 /*yield*/, execTerraform(execOptions, 'output', ['json', 'no-color'])];
                case 6:
                    output = _b.sent();
                    return [2 /*return*/, transformTerraformOutput(output)];
            }
        });
    });
}
function removeAirnode(params) {
    return __awaiter(this, void 0, void 0, function () {
        var airnodeAddressShort, stage, cloudProvider, type, region, err_3;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    airnodeAddressShort = params.airnodeAddressShort, stage = params.stage, cloudProvider = params.cloudProvider;
                    type = cloudProvider.type, region = cloudProvider.region;
                    spinner = logger.spinner("Removing Airnode ".concat(airnodeAddressShort, " ").concat(stage, " from ").concat(type, " ").concat(region));
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, remove(params)];
                case 2:
                    _a.sent();
                    spinner.succeed("Removed Airnode ".concat(airnodeAddressShort, " ").concat(stage, " from ").concat(type, " ").concat(region));
                    return [3 /*break*/, 4];
                case 3:
                    err_3 = _a.sent();
                    spinner.fail("Failed removing Airnode ".concat(airnodeAddressShort, " ").concat(stage, " from ").concat(type, " ").concat(region));
                    throw err_3;
                case 4: return [2 /*return*/];
            }
        });
    });
}
exports.removeAirnode = removeAirnode;
function remove(_a) {
    var airnodeAddressShort = _a.airnodeAddressShort, stage = _a.stage, cloudProvider = _a.cloudProvider;
    return __awaiter(this, void 0, void 0, function () {
        var cloudProviderType, bucket, airnodeTmpDir, execOptions;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (logger.inDebugMode()) {
                        spinner.info();
                    }
                    cloudProviderType = cloudProvider.type;
                    bucket = getBucketName(airnodeAddressShort, stage);
                    // Remove airnode
                    logger.debug('Removing Airnode via Terraform recipes');
                    airnodeTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'airnode'));
                    execOptions = { cwd: airnodeTmpDir };
                    return [4 /*yield*/, terraformAirnodeManage('destroy', execOptions, cloudProvider, bucket, { airnodeAddressShort: airnodeAddressShort, stage: stage })];
                case 1:
                    _b.sent();
                    return [4 /*yield*/, cloudProviderLib[cloudProviderType].removeState(bucket, cloudProvider)];
                case 2:
                    _b.sent();
                    return [2 /*return*/];
            }
        });
    });
}
//# sourceMappingURL=index.js.map