#!/usr/bin/env node
"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const uuid_1 = require("uuid");
const file_log_service_1 = require("./file-log-service");
const yok_1 = require("../common/yok");
const pathToBootstrap = process.argv[2];
if (!pathToBootstrap || !fs.existsSync(pathToBootstrap)) {
    throw new Error("Invalid path to bootstrap.");
}
require(pathToBootstrap);
const logFile = process.argv[3];
const jsFilePath = process.argv[4];
const fileLogService = yok_1.injector.resolve(file_log_service_1.FileLogService, {
    logFile,
});
const uniqueId = (0, uuid_1.v4)();
fileLogService.logData({
    message: `Initializing Cleanup process for path: ${jsFilePath} Unique id: ${uniqueId}`,
});
if (!fs.existsSync(jsFilePath)) {
    throw new Error(`Unable to find file ${jsFilePath}. Ensure it exists.`);
}
let data;
try {
    data = process.argv[5] && JSON.parse(process.argv[5]);
}
catch (err) {
    throw new Error(`Unable to parse data from argv ${process.argv[5]}.`);
}
const logMessage = (msg, type) => {
    fileLogService.logData({ message: `[${uniqueId}] ${msg}`, type });
};
(() => __awaiter(void 0, void 0, void 0, function* () {
    try {
        logMessage(`Requiring file ${jsFilePath}`);
        const func = require(jsFilePath);
        if (func && typeof func === "function") {
            try {
                logMessage(`Passing data: ${JSON.stringify(data)} to the default function exported by currently required file ${jsFilePath}`);
                yield func(data);
                logMessage(`Finished execution with data: ${JSON.stringify(data)} to the default function exported by currently required file ${jsFilePath}`);
            }
            catch (err) {
                logMessage(`Unable to execute action of file ${jsFilePath} when passed data is ${JSON.stringify(data)}. Error is: ${err}.`, "Error");
            }
        }
    }
    catch (err) {
        logMessage(`Unable to require file: ${jsFilePath}. Error is: ${err}.`, "Error");
    }
}))();
