"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 });
exports.deleteBucket = exports.deleteBucketDirectory = exports.copyFileInBucket = exports.getFileFromBucket = exports.storeFileToBucket = exports.getBucketDirectoryStructure = exports.createAirnodeBucket = exports.getAirnodeBucket = void 0;
const fs = __importStar(require("fs"));
const aws_sdk_1 = __importDefault(require("aws-sdk"));
const concat_1 = __importDefault(require("lodash/concat"));
const compact_1 = __importDefault(require("lodash/compact"));
const promise_utils_1 = require("@api3/promise-utils");
const logger = __importStar(require("../utils/logger"));
const infrastructure_1 = require("../utils/infrastructure");
const initializeS3Service = (cloudProvider) => {
    aws_sdk_1.default.config.update({ region: cloudProvider.region });
    return new aws_sdk_1.default.S3();
};
const getAirnodeBucket = (cloudProvider) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c;
    const s3 = initializeS3Service(cloudProvider);
    logger.debug('Listing S3 buckets');
    const goBuckets = yield (0, promise_utils_1.go)(() => s3.listBuckets().promise());
    if (!goBuckets.success) {
        throw new Error(`Failed to list S3 buckets: ${goBuckets.error}`);
    }
    const airnodeBuckets = (_a = goBuckets.data.Buckets) === null || _a === void 0 ? void 0 : _a.filter((bucket) => { var _a; return (_a = bucket.Name) === null || _a === void 0 ? void 0 : _a.match(infrastructure_1.BUCKET_NAME_REGEX); });
    if (airnodeBuckets && airnodeBuckets.length > 1) {
        throw new Error(`Multiple Airnode buckets found, stopping. Buckets: ${JSON.stringify(airnodeBuckets)}`);
    }
    return (_c = (_b = airnodeBuckets === null || airnodeBuckets === void 0 ? void 0 : airnodeBuckets[0]) === null || _b === void 0 ? void 0 : _b.Name) !== null && _c !== void 0 ? _c : null;
});
exports.getAirnodeBucket = getAirnodeBucket;
const createAirnodeBucket = (cloudProvider) => __awaiter(void 0, void 0, void 0, function* () {
    const s3 = initializeS3Service(cloudProvider);
    const bucketName = (0, infrastructure_1.generateBucketName)();
    logger.debug(`Creating S3 bucket '${bucketName}'`);
    const goCreate = yield (0, promise_utils_1.go)(() => s3.createBucket({ Bucket: bucketName }).promise());
    if (!goCreate.success) {
        throw new Error(`Failed to create an S3 bucket: ${goCreate.error}`);
    }
    // Enable bucket encryption
    logger.debug(`Setting encryption for S3 bucket '${bucketName}'`);
    const goPutEncryption = yield (0, promise_utils_1.go)(() => s3
        .putBucketEncryption({
        Bucket: bucketName,
        ServerSideEncryptionConfiguration: {
            Rules: [{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: 'AES256' }, BucketKeyEnabled: true }],
        },
    })
        .promise());
    if (!goPutEncryption.success) {
        throw new Error(`Failed to enable encryption for bucket '${bucketName}': ${goPutEncryption.error}`);
    }
    // Blocking public access to the bucket
    // https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-control-block-public-access.html
    logger.debug(`Setting public access block for S3 bucket '${bucketName}'`);
    const goPutPublicAccessBlock = yield (0, promise_utils_1.go)(() => s3
        .putPublicAccessBlock({
        Bucket: bucketName,
        PublicAccessBlockConfiguration: {
            BlockPublicAcls: true,
            BlockPublicPolicy: true,
            IgnorePublicAcls: true,
            RestrictPublicBuckets: true,
        },
    })
        .promise());
    if (!goPutPublicAccessBlock.success) {
        throw new Error(`Failed to setup a public access block for bucket '${bucketName}': ${goPutPublicAccessBlock.error}`);
    }
    return bucketName;
});
exports.createAirnodeBucket = createAirnodeBucket;
const getBucketDirectoryStructure = (cloudProvider, bucketName) => __awaiter(void 0, void 0, void 0, function* () {
    var _d;
    const s3 = initializeS3Service(cloudProvider);
    let paths = [];
    let truncated = true;
    let listParams = {
        Bucket: bucketName,
    };
    while (truncated) {
        logger.debug(`Listing objects for S3 bucket '${bucketName}'`);
        const goList = yield (0, promise_utils_1.go)(() => s3.listObjectsV2(listParams).promise());
        if (!goList.success) {
            throw new Error(`Failed to list content of bucket '${bucketName}': ${goList.error}`);
        }
        paths = (0, concat_1.default)(paths, (0, compact_1.default)((_d = goList.data.Contents) === null || _d === void 0 ? void 0 : _d.map((content) => content.Key)));
        truncated = !!goList.data.IsTruncated;
        if (goList.data.ContinuationToken) {
            listParams = Object.assign(Object.assign({}, listParams), { ContinuationToken: goList.data.ContinuationToken });
        }
    }
    return (0, infrastructure_1.translatePathsToDirectoryStructure)(paths);
});
exports.getBucketDirectoryStructure = getBucketDirectoryStructure;
const storeFileToBucket = (cloudProvider, bucketName, bucketFilePath, filePath) => __awaiter(void 0, void 0, void 0, function* () {
    const s3 = initializeS3Service(cloudProvider);
    logger.debug(`Storing file '${filePath}' as '${bucketFilePath}' to S3 bucket '${bucketName}'`);
    const goPut = yield (0, promise_utils_1.go)(() => s3
        .putObject({ Bucket: bucketName, Key: bucketFilePath, Body: fs.readFileSync(filePath, { encoding: 'utf-8' }) })
        .promise());
    if (!goPut.success) {
        throw new Error(`Failed to store file '${filePath}' to S3 bucket '${bucketName}': ${goPut.error}`);
    }
});
exports.storeFileToBucket = storeFileToBucket;
const getFileFromBucket = (cloudProvider, bucketName, filePath) => __awaiter(void 0, void 0, void 0, function* () {
    const s3 = initializeS3Service(cloudProvider);
    logger.debug(`Fetching file '${filePath}' from S3 bucket '${bucketName}'`);
    const goGet = yield (0, promise_utils_1.go)(() => s3.getObject({ Bucket: bucketName, Key: filePath }).promise());
    if (!goGet.success) {
        throw new Error(`Failed to fetch file '${filePath}' from S3 bucket '${bucketName}': ${goGet.error}`);
    }
    if (!goGet.data.Body) {
        throw new Error(`The response for file '${filePath}' from S3 bucket '${bucketName}' contained an empty body`);
    }
    return goGet.data.Body.toString('utf-8');
});
exports.getFileFromBucket = getFileFromBucket;
const copyFileInBucket = (cloudProvider, bucketName, fromFilePath, toFilePath) => __awaiter(void 0, void 0, void 0, function* () {
    const s3 = initializeS3Service(cloudProvider);
    logger.debug(`Copying file '${fromFilePath}' to file '${toFilePath}' within S3 bucket '${bucketName}'`);
    const goCopy = yield (0, promise_utils_1.go)(() => s3.copyObject({ Bucket: bucketName, CopySource: `/${bucketName}/${fromFilePath}`, Key: toFilePath }).promise());
    if (!goCopy.success) {
        throw new Error(`Failed to copy file '${fromFilePath}' to file '${toFilePath}' within S3 bucket '${bucketName}': ${goCopy.error}`);
    }
});
exports.copyFileInBucket = copyFileInBucket;
const gatherBucketKeys = (directory) => [
    directory.bucketKey,
    ...Object.values(directory.children).reduce((results, fsItem) => [
        ...results,
        ...(fsItem.type === infrastructure_1.FileSystemType.File ? [fsItem.bucketKey] : gatherBucketKeys(fsItem)),
    ], []),
];
const deleteBucketDirectory = (cloudProvider, bucketName, directory) => __awaiter(void 0, void 0, void 0, function* () {
    const s3 = initializeS3Service(cloudProvider);
    const bucketKeys = gatherBucketKeys(directory);
    logger.debug(`Deleting files from S3 bucket '${bucketName}': ${JSON.stringify(bucketKeys)}`);
    const goDelete = yield (0, promise_utils_1.go)(() => s3
        .deleteObjects({ Bucket: bucketName, Delete: { Objects: bucketKeys.map((bucketKey) => ({ Key: bucketKey })) } })
        .promise());
    if (!goDelete.success) {
        throw new Error(`Failed to delete bucket directory '${directory.bucketKey}' and its content: ${goDelete.error}`);
    }
});
exports.deleteBucketDirectory = deleteBucketDirectory;
const deleteBucket = (cloudProvider, bucketName) => __awaiter(void 0, void 0, void 0, function* () {
    const s3 = initializeS3Service(cloudProvider);
    logger.debug(`Deleting S3 bucket '${bucketName}'`);
    const goDelete = yield (0, promise_utils_1.go)(() => s3.deleteBucket({ Bucket: bucketName }).promise());
    if (!goDelete.success) {
        throw new Error(`Failed to delete S3 bucket '${bucketName}': ${goDelete.error}`);
    }
});
exports.deleteBucket = deleteBucket;
//# sourceMappingURL=aws.js.map