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

const targets = process.argv.slice(2);

if (targets.length === 0) {
  console.error("Usage: node scripts/clean-appledouble.js <path...>");
  process.exit(1);
}

let removed = 0;

function removeAppleDoubleFiles(targetPath) {
  if (!fs.existsSync(targetPath)) {
    return;
  }

  let stat;
  try {
    stat = fs.lstatSync(targetPath);
  } catch (error) {
    if (error && error.code === "ENOENT") {
      return;
    }
    throw error;
  }
  const baseName = path.basename(targetPath);

  if (baseName.startsWith("._")) {
    fs.rmSync(targetPath, { recursive: true, force: true });
    removed += 1;
    return;
  }

  if (!stat.isDirectory()) {
    return;
  }

  let entries;
  try {
    entries = fs.readdirSync(targetPath);
  } catch (error) {
    if (error && error.code === "ENOENT") {
      return;
    }
    throw error;
  }

  for (const entry of entries) {
    removeAppleDoubleFiles(path.join(targetPath, entry));
  }
}

for (const target of targets) {
  removeAppleDoubleFiles(path.resolve(process.cwd(), target));
}

console.log(`Removed ${removed} AppleDouble artifact${removed === 1 ? "" : "s"}.`);
