const fs = require('fs-extra');
const { execSync } = require('child_process');

module.exports = async function compilePackageInfo(packageInfoPath, outputPath) {
	const packageInfo = require(packageInfoPath);

	const removeKeys = [
		'dependencies',
		'devDependencies',
		'main',
		'optionalDependencies',
		'private',
		'scripts',
	];

	for (let i = 0; i < removeKeys.length; i++) {
		delete packageInfo[removeKeys[i]];
	}

	// Relevant for desktop app
	if (packageInfo.build) {
		const appId = packageInfo.build.appId;
		const productName = packageInfo.build.productName;
		delete packageInfo.build;
		packageInfo.build = { appId: appId };
		packageInfo.name = productName;
	}

	let branch;
	let hash;
	try {
		// Use stdio: 'pipe' so that execSync doesn't print error directly to stdout
		branch = execSync('git rev-parse --abbrev-ref HEAD', { stdio: 'pipe' }).toString().trim();
		hash = execSync('git log --pretty="%h" -1', { stdio: 'pipe' }).toString().trim();
		// The builds in CI are done from a 'detached HEAD' state, thus the branch name will be 'HEAD' for CI builds.
	} catch (error) {
		// Don't display error object as it's a "fatal" error, but
		// not for us, since is it not critical information
		// https://github.com/laurent22/joplin/issues/2256
		console.info('Warning: Could not get git info (it will not be displayed in About dialog box)');
	}
	if (typeof branch !== 'undefined' && typeof hash !== 'undefined') {
		packageInfo.git = { branch: branch, hash: hash };
	}

	let fileContent = '// Auto-generated by compilePackageInfo.js\n// Do not change directly';
	fileContent += '\n';
	fileContent += `module.exports = ${JSON.stringify(packageInfo, null, '\t')};\n`;

	await fs.writeFile(outputPath, fileContent);

	console.info(`Generated ${outputPath}`);
};
