const fs = require('fs-extra'); const path = require('path'); const os = require('os'); const PRIMARY_UNROUTED_DIR = '/cadroute/__NON_SMISTATI'; const HOME_UNROUTED_DIR = path.join(os.homedir(), '.cadroute', '__NON_SMISTATI'); let resolvedUnroutedDirPromise = null; async function resolveUnroutedDir() { if (!resolvedUnroutedDirPromise) { resolvedUnroutedDirPromise = (async () => { try { await fs.ensureDir(PRIMARY_UNROUTED_DIR); return PRIMARY_UNROUTED_DIR; } catch { await fs.ensureDir(HOME_UNROUTED_DIR); return HOME_UNROUTED_DIR; } })(); } return resolvedUnroutedDirPromise; } async function getUniquePath(destinationDir, fileName) { const parsed = path.parse(fileName); let candidate = path.join(destinationDir, fileName); let counter = 1; while (await fs.pathExists(candidate)) { candidate = path.join(destinationDir, `${parsed.name}__${counter}${parsed.ext}`); counter += 1; } return candidate; } async function getUnroutedTarget(fileName) { const destinationDir = await resolveUnroutedDir(); const destinationPath = await getUniquePath(destinationDir, fileName); return { destinationDir, destinationPath, }; } module.exports = { getUnroutedTarget, PRIMARY_UNROUTED_DIR, HOME_UNROUTED_DIR, };