/**
 * Jovian © 2021
 * License: MIT
 */

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

const pathArg = process.argv[2];
if (pathArg) {
  process.chdir(path.normalize(pathArg));
}

const cwd = process.cwd();
glob("**/node_modules", {}, function (e, locations) {
  if (e) { console.log(e); return; }
  for (const nodeModulesPath of locations) {
    touchFile(path.normalize(`${cwd}/${nodeModulesPath}`));
  }
});

function touchFile(nodeModulesPath: string) {
  const nosyncPath = nodeModulesPath + '/.nosync';
  try {
    if (fs.existsSync(nosyncPath)) {
      console.log(`.nosync already exists at '${nosyncPath}'`);
    } else {
      fs.closeSync(fs.openSync(nosyncPath, 'w'));
      console.log(`created .nosync file at '${nodeModulesPath}'`);
    }
  } catch (e) {
    console.log(`failed to create .nosync file at '${nodeModulesPath}'`);
  }
}
