"use strict";
/*
 *  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *  SPDX-License-Identifier: Apache-2.0
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable security/detect-non-literal-fs-filename */
const fs_1 = __importDefault(require("fs"));
const path_1 = require("path");
const workbench_core_audit_1 = require("@aws/workbench-core-audit");
const workbench_core_authorization_1 = require("@aws/workbench-core-authorization");
const workbench_core_base_1 = require("@aws/workbench-core-base");
const workbench_core_environments_1 = require("@aws/workbench-core-environments");
const workbench_core_logging_1 = require("@aws/workbench-core-logging");
const workbench_core_user_management_1 = require("@aws/workbench-core-user-management");
const constants_1 = require("./constants");
const authorizationSetup_1 = __importDefault(require("./postDeployment/authorizationSetup"));
async function run() {
    const { AWS_REGION, S3_ARTIFACT_BUCKET_SC_PREFIX, SC_PORTFOLIO_NAME, S3_ARTIFACT_BUCKET_ARN_OUTPUT_KEY, LAUNCH_CONSTRAINT_ROLE_OUTPUT_KEY, STACK_NAME, ROOT_USER_EMAIL, USER_POOL_NAME, DYNAMIC_AUTH_TABLE_NAME, USER_AGENT_STRING } = await (0, constants_1.getConstantsWithSecrets)();
    const scSetup = new workbench_core_environments_1.ServiceCatalogSetup({
        AWS_REGION,
        S3_ARTIFACT_BUCKET_SC_PREFIX,
        SC_PORTFOLIO_NAME,
        S3_ARTIFACT_BUCKET_ARN_OUTPUT_KEY,
        LAUNCH_CONSTRAINT_ROLE_OUTPUT_KEY,
        STACK_NAME
    });
    const cognitoSetup = new workbench_core_environments_1.CognitoSetup({
        AWS_REGION,
        ROOT_USER_EMAIL,
        USER_POOL_NAME,
        STACK_NAME
    });
    const dynamicAuthAwsService = new workbench_core_base_1.AwsService({
        region: AWS_REGION,
        ddbTableName: DYNAMIC_AUTH_TABLE_NAME
    });
    const userPoolId = await cognitoSetup.getUserPoolId();
    const logger = new workbench_core_logging_1.LoggingService();
    const wbcGroupManagementPlugin = new workbench_core_authorization_1.WBCGroupManagementPlugin({
        userManagementService: new workbench_core_user_management_1.UserManagementService(new workbench_core_user_management_1.CognitoUserManagementPlugin(userPoolId, dynamicAuthAwsService)),
        ddbService: dynamicAuthAwsService.helpers.ddb,
        userGroupKeyType: constants_1.authorizationGroupPrefix
    });
    const ddbDynamicAuthorizationPermissionsPlugin = new workbench_core_authorization_1.DDBDynamicAuthorizationPermissionsPlugin({
        dynamoDBService: dynamicAuthAwsService.helpers.ddb
    });
    const caslAuthorizationPlugin = new workbench_core_authorization_1.CASLAuthorizationPlugin();
    const authService = new workbench_core_authorization_1.DynamicAuthorizationService({
        groupManagementPlugin: wbcGroupManagementPlugin,
        dynamicAuthorizationPermissionsPlugin: ddbDynamicAuthorizationPermissionsPlugin,
        auditService: new workbench_core_audit_1.AuditService(new workbench_core_audit_1.BaseAuditPlugin(new workbench_core_audit_1.AuditLogger(logger))),
        authorizationPlugin: caslAuthorizationPlugin
    });
    const authSetup = new authorizationSetup_1.default(authService, {
        ROOT_USER_EMAIL
    });
    const awsService = new workbench_core_base_1.AwsService({
        region: AWS_REGION,
        userAgent: USER_AGENT_STRING,
        ddbTableName: STACK_NAME
    });
    const cfnFilePaths = scSetup.getCfnTemplate((0, path_1.join)(__dirname, '../../src/environment'));
    await scSetup.run(cfnFilePaths);
    await setupEnvironmentTypes(awsService, SC_PORTFOLIO_NAME);
    await cognitoSetup.run();
    await authSetup.run();
    await uploadOnboardAccountCfnToS3(awsService);
    await uploadBootstrapScriptsToS3(awsService);
}
async function setupEnvironmentTypes(awsService, portfolioName) {
    console.log('Setting up Environment Types in the database');
    const envTypeHandler = new workbench_core_environments_1.EnvironmentTypeSetup(awsService);
    await envTypeHandler.run(portfolioName);
}
async function uploadTemplateFileToS3(awsService, templateFileName) {
    console.log(`Uploading ${templateFileName} to S3`);
    const onboardAccountFilePath = (0, path_1.join)(__dirname, `../../src/templates/${templateFileName}`);
    const onboardAccountFile = fs_1.default.readFileSync(onboardAccountFilePath);
    const s3Service = awsService.helpers.s3;
    const s3ArtifactBucketArn = await getS3BucketArn(awsService);
    await s3Service.uploadFiles(s3ArtifactBucketArn, [
        { fileContent: onboardAccountFile, fileName: templateFileName, s3Prefix: '' }
    ]);
    console.log(`Finished uploading ${templateFileName} to S3`);
}
async function uploadOnboardAccountCfnToS3(awsService) {
    console.log('Uploading template files to S3');
    await Promise.all([
        uploadTemplateFileToS3(awsService, 'onboard-account.cfn.yaml'),
        uploadTemplateFileToS3(awsService, 'onboard-account-byon.cfn.yaml')
    ]);
    console.log('Finished uploading template files to S3');
}
async function uploadBootstrapScriptsToS3(awsService) {
    const { S3_ARTIFACT_BUCKET_BOOTSTRAP_PREFIX } = (0, constants_1.getConstants)();
    const s3ArtifactBucketArn = await getS3BucketArn(awsService);
    const s3BucketName = s3ArtifactBucketArn.split(':').pop();
    // resolve full folder path
    const scriptsPath = (0, path_1.join)(__dirname, '../../src/environment-files');
    console.log('Uploading offline file-system binary packages');
    const s3Service = awsService.helpers.s3;
    console.log(`Uploading offline environment bootstrap scripts to S3 bucket ${s3BucketName}, path: ${S3_ARTIFACT_BUCKET_BOOTSTRAP_PREFIX}`);
    await s3Service.uploadFolder(s3BucketName, S3_ARTIFACT_BUCKET_BOOTSTRAP_PREFIX, scriptsPath);
    console.log('Finished uploading offline environment bootstrap scripts to S3');
}
async function getS3BucketArn(awsService) {
    const { S3_ARTIFACT_BUCKET_ARN_OUTPUT_KEY, STACK_NAME } = (0, constants_1.getConstants)();
    const cfService = awsService.helpers.cloudformation;
    const { [S3_ARTIFACT_BUCKET_ARN_OUTPUT_KEY]: s3ArtifactBucketArn } = await cfService.getCfnOutput(STACK_NAME, [S3_ARTIFACT_BUCKET_ARN_OUTPUT_KEY]);
    return s3ArtifactBucketArn;
}
/* eslint-disable-next-line @typescript-eslint/no-floating-promises*/
(async () => {
    await run();
})();
//# sourceMappingURL=postDeployment.js.map