const utils = require('./utils'); module.exports = function sync(source, target, crypt, decrypt) { return new Promise(async (resolve, reject) => { try { // Get stats of source and target const [ statSource, statTarget ] = await Promise.all([ utils.getStats(source), utils.getStats(target) ]); // Source does not exists and target exists, delete target if (statSource === null && statTarget !== null) { await utils.delete(target); return resolve(); } // Dost not exists in the target, copy if (statSource !== null && statTarget === null) { await utils.copy(source, target, crypt, decrypt); return resolve(); } if (statSource.isDirectory() && statTarget.isDirectory()) { // Verify if both are directories const nextPaths = await utils.readRecursive(source, target); for (let index = 0; index < nextPaths.length; index++) { const [ nextSource, nextTarget ] = nextPaths[index]; // Start to sync next paths await sync(nextSource, nextTarget, crypt, decrypt); } } else if (statSource.isFile() && statTarget.isFile()) { // Verify if both are files if (statSource.mtime <= statTarget.mtime) { // Source is newer, copy the new version to the target await utils.copy(source, target, crypt, decrypt); } } return resolve(); } catch (err) { return reject(err); } }); };