
const args = process.argv.slice(2)

if (args.length < 2) {
	console.error('Usage: node base_with_mask.js <base_name> <mask_name> [subfolder]\n')
	console.error('If subfolder specified, resulting file name will contain only color name\n')
	console.error('Subfolder is relative to base texture path\n')
	process.exit(2)
}

const fs = require('fs')
const {colorsWithWhite, rootFolder, splitName, getSize} = require('./include.js')
const child_process = require('child_process');

(async function() {
	const baseTexture = args[0]
	const maskTexture = args[1]
	const subfolder = args[2] ?? ''

	const fBase = `${rootFolder}${baseTexture}.png`
	const fMask = `${rootFolder}${maskTexture}.png`

	if (!fs.existsSync(fBase)) {
		process.stderr.write(`${fBase} does not exist\n`)
		process.exit(1)
	}

	if (!fs.existsSync(fMask)) {
		process.stderr.write(`${fMask} does not exist\n`)
		process.exit(1)
	}

	const [fileName, _, fullBaseFolder] = splitName(baseTexture)
	const bSize = (await getSize(fBase))[2]
	const mSize = (await getSize(fMask))[2]

	if (subfolder !== '') {
		fs.mkdirSync(`${fullBaseFolder}/${subfolder}`, {recursive: true})
	}

	if (bSize != mSize) {
		process.stderr.write(`${fBase} has size of ${bSize}, ${fMask} has size of ${mSize}!\n`)
		process.exit(3)
	}

	for (const [name, _, xc] of colorsWithWhite) {
		const outputFilename = subfolder === '' ? `${fullBaseFolder}/${fileName}_${name}.png` : `${fullBaseFolder}/${subfolder}/${name}.png`

		const magick = child_process.spawn('magick', [
			'convert',

			fBase,

			'(',
				fMask,
				'-size', bSize,
				xc,
				'-channel', 'rgb',
				'-compose', 'Multiply',
				'-composite',
			')',

			'-compose', 'Over',
			'-composite',

			outputFilename])

		magick.stdout.pipe(process.stdout)
		magick.stderr.pipe(process.stderr)
	}
})();

