const { renameSync } = require('fs');
const [dir, search, replace] = process.argv.slice(2);
const match = RegExp(search, 'g');

const { promisify } = require('util');
const { resolve } = require('path');
const fs = require('fs');
const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);

async function getFiles(dir_path) {
	const subdirs = await readdir(dir_path);

	const files = await Promise.all(subdirs.map(async (subdir) => {
		const res = resolve(dir_path, subdir);
		return (await stat(res)).isDirectory() ? getFiles(res) : res;
	}));

	return files.reduce((a, f) => a.concat(f), []);
}

getFiles(dir).then((files) => {
	console.log('--- Rename service ---');

	files
		.filter(file => file.match(RegExp(search + '$', 'g')))
		.forEach(file => {
			const newFilePath = file.replace(match, replace);

			console.log(`${file} >> ${newFilePath}`)

			renameSync(file, newFilePath);
		});
});
