"use strict";
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 child_process_1 = require("child_process");
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const core_1 = require("@restlessness/core");
function spawnAsyncWithInheritStdio(command, args) {
    return new Promise((resolve, reject) => {
        const proc = child_process_1.spawn(command, args, { stdio: 'inherit' });
        proc.on('error', reject);
        proc.on('exit', code => {
            if (code === 0) {
                resolve();
            }
            else {
                reject(code);
            }
        });
    });
}
exports.default = (argv) => __awaiter(void 0, void 0, void 0, function* () {
    if (argv._.length > 2) {
        throw 'Unexpected number of arguments';
    }
    yield core_1.JsonServices.read();
    let servicesToDeploy = Object.keys(core_1.JsonServices.services)
        .filter(s => s !== core_1.JsonServices.OFFLINE_SERVICE_NAME)
        .filter(s => s !== core_1.JsonServices.SHARED_SERVICE_NAME);
    servicesToDeploy = [...servicesToDeploy, core_1.JsonServices.SHARED_SERVICE_NAME];
    if (argv._.length === 2) {
        const argService = argv._[1];
        if (!core_1.JsonServices.services[argService]) {
            throw `Service ${argService} does not exists!`;
        }
        servicesToDeploy = [argService];
    }
    let deploymentEnv = 'staging';
    if (argv.env) {
        deploymentEnv = argv.env;
    }
    const jsonEnv = yield core_1.JsonEnvs.getEntryById(deploymentEnv);
    if (!jsonEnv) {
        throw `Cannot find Environment ${deploymentEnv}`;
    }
    if (!jsonEnv.stage) {
        throw `Cannot deploy! Environment ${jsonEnv.id} does not have an associated stage`;
    }
    const outputPath = path_1.default.join(core_1.PathResolver.getPrjPath, '.serverless-outputs');
    try {
        yield fs_1.promises.rmdir(outputPath, { recursive: true });
    }
    catch (e) { }
    for (let serviceName of servicesToDeploy) {
        const servicePath = path_1.default.relative(process.cwd(), path_1.default.join(core_1.PathResolver.getServicesJsonPath, `${serviceName}.json`));
        console.log(chalk_1.default.blue('Restlessness:'), 'Removing service', serviceName);
        const deployArgs = ['--config', servicePath, 'remove', '--stage', jsonEnv.stage, '--verbose'];
        try {
            yield spawnAsyncWithInheritStdio('serverless', deployArgs);
        }
        catch (e) {
            console.log(chalk_1.default.red('Restlessness error'), 'Removing service', serviceName);
        }
    }
});
//# sourceMappingURL=index.js.map