"use strict";
/*
 * Copyright © 2020 Atomist, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheCleanupAutomationEventListener = void 0;
const AutomationEventListener_1 = require("@atomist/automation-client/lib/server/AutomationEventListener");
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const cluster = require("cluster");
const fg = require("fast-glob");
const fs = require("fs-extra");
const path = require("path");
/**
 * Event listener that cleans up cached artifacts that are older then 2 hours.
 */
class CacheCleanupAutomationEventListener extends AutomationEventListener_1.AutomationEventListenerSupport {
    constructor(sdm) {
        super();
        this.sdm = sdm;
    }
    async startupSuccessful(client) {
        const possibleCacheConfiguration = this.sdm.configuration.sdm.cache;
        if (cluster.isMaster && possibleCacheConfiguration && possibleCacheConfiguration.enabled) {
            const cachePath = possibleCacheConfiguration.path || "/opt/data";
            setTimeout(async () => {
                try {
                    const ts = Date.now() - (1000 * 60 * 60 * 2); // 2 hour threshold
                    if (fs.existsSync(cachePath)) {
                        const matches = await fg("**/*", { cwd: cachePath });
                        for (const m of matches) {
                            const p = path.join(cachePath, m);
                            try {
                                const st = await fs.stat(p);
                                if (st.mtimeMs < ts && st.isFile()) {
                                    logger_1.logger.debug(`Deleting cached file '${p}'`);
                                    await fs.remove(p);
                                }
                            }
                            catch (e) {
                                logger_1.logger.debug("Failed to delete cached file '%s': %s", p, e.message);
                            }
                        }
                    }
                }
                catch (err) {
                    logger_1.logger.debug("Failed to clean cache directory '%s': %s", cachePath, err.message);
                }
            });
        }
    }
}
exports.CacheCleanupAutomationEventListener = CacheCleanupAutomationEventListener;
//# sourceMappingURL=CacheCleanupAutomationEventListener.js.map