const fs = require('fs');
const path = require('path');

const predownload = (job, settings, { cacheDirectory }) => {
    if (job.template.src.startsWith('file://')) {
        settings.logger.log(`> Skipping template cache; local file protocol is being used`)
        return Promise.resolve();
    }
    
    const fileName = path.basename(job.template.src);
    const maybeCachedFileLocation = path.join(cacheDirectory, fileName);
    
    if (!fs.existsSync(maybeCachedFileLocation)) {
        settings.logger.log(`> Template cache not found at ${maybeCachedFileLocation}`);
        return Promise.resolve();
    }

    settings.logger.log(`> Template cache found at ${maybeCachedFileLocation}`);
    settings.logger.log(`> Old template source: ${job.template.src}`);
    job.template.src = `file://${maybeCachedFileLocation}`;
    settings.logger.log(`> New template source: ${job.template.src}`);
    
    return Promise.resolve();
}

const postdownload = (job, settings, { cacheDirectory }) => {
    if (job.template.src.startsWith('file://')) {
        settings.logger.log(`> Skipping template cache; local file protocol is being used`);
        return Promise.resolve();
    }

    if (!fs.existsSync(cacheDirectory)) {
        settings.logger.log(`> Creating cache directory at ${cacheDirectory}`);
        fs.mkdirSync(cacheDirectory);
    }
    
    const fileName = path.basename(job.template.src);
    settings.logger.log(`> Copying from ${path.join(job.workpath, fileName)} to ${path.join(cacheDirectory, fileName)}`);
    const readStream = fs.createReadStream(path.join(job.workpath, fileName));
    const writeStream = fs.createWriteStream(path.join(cacheDirectory, fileName));

    return new Promise(function(resolve, reject) {
        readStream.on('error', reject);
        writeStream.on('error', reject);
        writeStream.on('finish', () => resolve(job));
        readStream.pipe(writeStream);
    }).catch((error) => {
        readStream.destroy();
        writeStream.end();
        console.log(error)
        throw error;
    });
}

module.exports = (job, settings, { cacheDirectory }, type) => {
    if (!cacheDirectory) {
        throw new Error(`cacheDirectory not provided.`);
    }

    cacheDirectory = cacheDirectory.replace('~', require('os').homedir());
    
    if (fs.existsSync(cacheDirectory) && !fs.lstatSync(cacheDirectory).isDirectory()) {
        throw new Error(`Cache path of ${cacheDirectory} exists but is not a directory, stopping`);
    }

    if (type === 'predownload') {
        return predownload(job, settings, { cacheDirectory }, type);
    }

    if (type === 'postdownload') {
        return postdownload(job, settings, { cacheDirectory }, type);
    }

    return Promise.resolve();
}

@@ -94,32 +94,37 @@
 %7B cacheDirectory
+, ttl
  %7D) =%3E %7B%0A    if 
@@ -108,32 +108,32 @@
 ry, ttl %7D) =%3E %7B%0A
-
     if (job.temp
@@ -426,24 +426,25 @@
  fileName);%0A
+%0A
     %0A    if 
@@ -572,24 +572,24 @@
 ocation%7D%60);%0A
-
         retu
@@ -613,24 +613,440 @@
 e();%0A    %7D%0A%0A
+    if (ttl) %7B%0A        const birthtime = fs.statSync(maybeCachedFileLocation).birthtimeMs;%0A        if (Date.now() - birthtime %3E ttl) %7B%0A            settings.logger.log(%60%3E Template cache expired at $%7BmaybeCachedFileLocation%7D%60);%0A            settings.logger.log(%60%3E Deleting cache at $%7BmaybeCachedFileLocation%7D%60);%0A            fs.unlinkSync(maybeCachedFileLocation);%0A            return Promise.resolve();%0A        %7D%0A    %7D%0A%0A
     settings
@@ -2517,32 +2517,37 @@
 %7B cacheDirectory
+, ttl
  %7D, type) =%3E %7B%0A 
@@ -2995,32 +2995,37 @@
 %7B cacheDirectory
+, ttl
  %7D, type);%0A    %7D

add ttl on cache