#!/usr/bin/env node
'use strict';

import fs from 'fs';
import path from 'path';
import shell from 'shelljs';
import { fileURLToPath } from 'url';
import yargs from 'yargs-parser';

async function main(flags) {
	const __dirname = path.resolve(
		fileURLToPath(new URL('.', import.meta.url)),
		'..'
	);

	const __project_dirname = path.resolve(
		fileURLToPath(new URL('.', import.meta.url)),
		'../../../../'
	);

	const cmd = flags._[2] || 'dev';

	if (cmd === 'build') {
		if (shell.exec(`cd ${__dirname} && npm run build`).code !== 0) {
			shell.echo('Error: Build failed');
			shell.exit(1);
		} else {
			// Remove the old build and copy the new one
			if (fs.existsSync(`${__project_dirname}/nitrogen-build`)) {
				fs.rmSync(`${__project_dirname}/nitrogen-build`, { recursive: true });
			}
			fs.cpSync(`${__dirname}/dist`, `${__project_dirname}/nitrogen-build`, {
				recursive: true,
			});
			fs.rmSync(`${__dirname}/dist`, { recursive: true });
		}

		return;
	}

	shell.exec(`cd ${__dirname} && npm run dev`);
}

const flags = yargs(process.argv);

main(flags);
