const assproc = require('@railcomm/assproc');
const { join: pathJoin } = require('path');
const fs = require('fs');
const exec = require('util').promisify(require('child_process').exec);

(async () => {
    const config = JSON.parse(fs.readFileSync(pathJoin(__dirname, 'config/config.json')));
    const isDebug = fs.existsSync(pathJoin(__dirname, '.debug'));

    const env = {
        root: __dirname,
        source: pathJoin(__dirname, 'src'),
        public: pathJoin(__dirname, 'public'),
        debug: isDebug,
        swc: { es: 'es2021' },
        housekeep: [ pathJoin(__dirname, 'public', 'assets') ],
        vars: {
            html: {
                title: config.title,
            },
            build: {
                FUTAMI_DEBUG: isDebug,
                FUTAMI_URL: config.common_url,
                MAMI_URL: config.modern_url,
                AMI_URL: config.compat_url,
                GIT_HASH: (await exec('git log --pretty="%H" -n1 HEAD')).stdout,
            },
        },
    };

    const tasks = {
        js: [
            { source: 'mami.js',  target: '/assets', name: 'mami.{hash}.js', vars: { build: 'MAMI_JS', html: ':source' } },
            { source: 'init.js',  target: '/assets', name: 'init.{hash}.js', es: 'es5', vars: { html: ':source' } },
        ],
        css: [
            { source: 'mami.css', target: '/assets', name: 'mami.{hash}.css', vars: { html: ':source' } },
        ],
        webmanifest: [
            { source: 'mami.webmanifest', target: '/', name: 'mami.webmanifest', icons: '/icons', vars: { html: ':source' }, body: { name: config.title, short_name: config.title } }
        ],
        html: [
            { source: 'mami.html', target: '/', name: 'index.html', template: 'html' },
        ],
    };

    if(process.argv.length > 2) {
        const filter = process.argv.slice(2);
        for(const name in tasks)
            if(!filter.includes(name))
                delete tasks[name];
    }

    await assproc.process(env, tasks);
})();