#!/usr/bin/env node

'use strict';

const path = require("path");

// Local version replace global one
try {
    const localModule = require.resolve(path.join(process.cwd(), "node_modules", "web-blog", "bin", "web-blog.js"));
    if (__filename !== localModule) {
        return require(localModule);
    }
} catch (e) {
}

var nodeUtils = require('./utils/node-utils');
var projectPath = process.cwd();


/**
 *
 * @param cmd {String}
 * @param options {Array}
 * @param [callback] {Function}
 */
function run(cmd, options, callback) {
    nodeUtils.runWithProgress(cmd, options, function (code, errData) {
        if (code !== 0) {
            console.error(`Can not run web-blog ${cmd} ${options}:\n` + errData);
        } else {
            callback && callback();
        }
    });
}

/**
 * Makes the following code working:
 *
 runInQueue(()=> {
    someAsyncFunc((err)=>{
     if(!err) next();
    });
  });
 */

var queue = [];
function next() {
    queue.shift()();
}
function runInQueue(behavior) {
    queue.push(behavior);
}


// PROCESS
process.chdir(// change path to web-blog
    path.join(projectPath, "node_modules", "web-blog")
);

runInQueue(()=> {
    console.log('Running in web-blog: $ npm install');
    run('npm', ['install'], ()=> {
        next();
    });
});

runInQueue(()=> {
    console.log('Running in web-blog: $ npm run copy');
    run('npm', ['run', 'copy'], ()=> {
        next();
    });
});

runInQueue(()=> {
    process.chdir(// change path back to the project
        path.join(projectPath)
    );

    console.log('Running in project: $ npm install');
    run('npm', ['install']);
});

// Start the commands chain!
next();