// Generated by LiveScript 1.6.0
var fs, os, path, makeDir, der2, hash, toPEM, to$, writeFile, readdir, unlink;
fs = require('fs');
os = require('os');
path = require('path');
makeDir = require('make-dir');
der2 = require('./der2');
hash = require('./hash');
module.exports = save;
toPEM = der2(der2.txt);
to$ = hash();
writeFile = promisify(fs.writeFile);
readdir = promisify(fs.readdir);
unlink = promisify(fs.unlink);
function save(params){
  var folder, chain, PEM, hashes, names;
  hashes = {};
  names = new Set;
  return later;
  function later(it){
    return Promise.resolve(it).then(saver);
  }
  function saver(der){
    if (der) {
      chain || (chain = mkdir(params.save || params.$ave).then(function(it){
        return folder = it;
      }));
      chain = chain.then(function(){
        if (folder) {
          return single(der);
        }
      });
    } else if (chain) {
      chain.then(cleanUp).then(function(){
        if (PEM != null) {
          PEM.end();
        }
        if (folder && params.$ave) {
          process.env.SSL_CERT_DIR = require('.').path = folder;
        }
        if (typeof params.onsave == 'function') {
          params.onsave(folder);
        }
      });
    } else {
      if (typeof params.onsave == 'function') {
        params.onsave();
      }
    }
  }
  function single(der){
    var pem, hash;
    (PEM || (PEM = fs.createWriteStream(name('roots.pem')))).write(pem = toPEM(der));
    hashes[hash = to$(der)] || (hashes[hash] = 0);
    return writeFile(name(hash + "." + (hashes[hash]++)), pem)['catch'](ignore);
  }
  function name(it){
    names.add(it);
    return path.join(folder, it);
  }
  function cleanUp(){
    if (folder) {
      readdir(folder).then(function(it){
        return Promise.all(it.filter(function(it){
          return !names.has(it);
        }).map(function(it){
          return path.join(folder, it);
        }).map(function(it){
          return unlink(it)['catch'](ignore);
        }));
      })['catch'](ignore);
    }
  }
}
function defaults(){
  return [path.join(__dirname, '../pem'), path.join(os.homedir(), '.local/win-ca/pem')];
}
function mkdir(dst){
  var idx;
  if ('string' === typeof dst) {
    dst = [dst];
  } else if (!Array.isArray(dst)) {
    dst = defaults();
  }
  idx = 0;
  return nextDir();
  function nextDir(){
    if (idx < dst.length) {
      return makeDir(dst[idx++])['catch'](nextDir);
    } else {
      return Promise.resolve();
    }
  }
}
function promisify(fn){
  return function(){
    var args, this$ = this;
    args = [].slice.call(arguments);
    return new Promise(function(resolve, reject){
      args.push(callback);
      fn.apply(this$, args);
      function callback(error, value){
        if (error) {
          reject(error);
        } else {
          resolve(value);
        }
      }
    });
  };
}
function ignore(){}