/*
 * fis
 * http://web.baidu.com/
 */

'use strict';

exports.name = 'server';
exports.usage = '<command> [options]';
exports.desc = 'launch a php-cgi server';
exports.register = function(commander, fis){
    
    function getConf(){
        return fis.project.getTempPath('server/conf.json');
    }
    
    function stop(callback){
        var tmp = fis.util(__dirname, 'pid');
        if(fis.util.exists(tmp)){
            var pid = fis.util.fs.readFileSync(tmp, 'utf8').trim().split(/\s*,\s*/);
            var list, msg = '';
            var isWin = fis.util.isWin();
            if(isWin){
                list = require('child_process').spawn('tasklist');
            } else {
                list = require('child_process').spawn('ps', ['a']);
            }
            list.stdout.on('data', function(chunk){
                msg += chunk.toString('utf8').toLowerCase();
            });
            list.on('exit', function(){
                var reg = /\b(node|java)\b/;
                var indexs = {
                    'node' : 0,
                    'java' : 1
                };
                msg.split(/[\r\n]+/).forEach(function(item){
                    var match = item.match(reg);
                    if(match){
                        item = item.split(/\s+/);
                        var id = item[isWin ? 1 : 0];
                        if(id == pid[indexs[match[1]]]){
                            process.kill(id);
                        }
                    }
                });
                if(callback){
                    callback();
                }
            });
        }
    }
    
    function matchVersion(str){
        var version = false;
        var reg = /\b\d+(\.\d+){2}/;
        var match = str.match(reg);
        if(match){
            version = match[0];
        }
        return version;
    }
    
    function start(opt){
        var tmp = getConf();
        if(opt){
            fis.util.write(tmp, JSON.stringify(opt));
        } else {
            if(fis.util.exists(tmp)){
                opt = fis.util.readJSON(tmp);
            } else {
                opt = {};
            }
        }
        
        var spawn = require('child_process').spawn;
        
        //check java
        process.stdout.write('check java version : ');
        var java = spawn('java', ['-version']);
        var javaVersion = false;
        java.stderr.on('data', function(data){
            if(!javaVersion){
                javaVersion = matchVersion(data.toString('utf8'));
                if(javaVersion){
                    process.stdout.write(javaVersion + '\n');
                }
            }
        });
        java.on('error', function(err){
            fis.log.error(err);
        });
        java.on('exit', function(){
            if(javaVersion){
                //check php-cgi
                process.stdout.write('check php-cgi version : ');
                var php = spawn('php-cgi', ['-v']);
                var phpVersion = false;
                php.stdout.on('data', function(data){
                    if(!phpVersion){
                        phpVersion = matchVersion(data.toString('utf8'));
                        if(phpVersion){
                            process.stdout.write(phpVersion + '\n');
                        }
                    }
                });
                php.on('error', function(err){
                    fis.log.error(err);
                });
                php.on('exit', function(){
                    if(phpVersion){
                        process.stdout.write('starting fis-server on port : ');
                        var cmd = [
                            process.execPath.replace(/\s+/g, '" "'),
                            '"' + fis.util(__dirname, 'child.js') + '"',
                            '--root', opt.root,
                            '--port', opt.port,
                            '--script', opt.script,
                            '--pool_size', opt.pool_size,
                            '--max_requests', opt.max_requests
                        ].join(' ');
                        if(!opt.rewrite){
                            cmd += ' --no-rewrite';
                        }
                        fis.util.nohup(cmd, { cwd : __dirname });
                        setTimeout(function(){
                            process.stdout.write(opt.port + '\n');
                        }, 2000);
                    } else {
                        fis.log.error('unsupported php-cgi environment');
                    }
                });
            } else {
                fis.log.error('unsupported java environment');
            }
        });
    }
    
    commander
        .option('-p, --port <int>', 'server listen port', parseInt, 8080)
        .option('-s, --script <name>', 'input php file', String, 'index.php')
        .option('--pool_size <int>', 'the number of php-cgi processes', parseInt, 6)
        .option('--max_requests <int>', 'the max number of requests', parseInt, 1000)
        .option('--no-rewrite', 'whether rewrite all requests', Boolean)
        .action(function(cmd, options){
            var root = fis.project.getTempPath('www');
            if(!fis.util.exists(root)){
                fis.util.mkdir(root);
            }
            switch (cmd){
                case 'start':
                    stop(function(){
                        start({
                            root : root,
                            port : options['port'],
                            script : options['script'],
                            rewrite : options['rewrite'],
                            pool_size : options['pool_size'],
                            max_requests : options['max_requests']
                        });
                    });
                    break;
                case 'stop':
                    stop();
                    break;
                case 'restart':
                    stop(start);
                    break;
                case 'install':
                    var name = options;
                    options = arguments[2];
                    if(typeof name === 'string'){
                        name = name.split('@');
                        var version = name[1] || '0';
                        name = name[0];
                        var remote = fis.config.get(
                            'system.repos', fis.project.DEFAULT_REMOTE_REPOS
                        ).replace(/\/$/, '');
                        var url = remote + '/' + name + '/' + version + '.tar';
                        process.stdout.write('download module [' + name + '@' + version + '] ... ');
                        fis.util.download(url, function(err, file){
                            if(err){
                                process.stdout.write('fail\n');
                                fis.log.error( 'unable to download modules [' +
                                    name + '@' + version + '] from [' + url + '], error [' + err + ']');
                            } else {
                                fis.util.fs
                                    .createReadStream(file)
                                    .pipe(fis.tar.Extract({
                                        path : root
                                    }))
                                    .on('error', function(err){
                                        process.stdout.write('fail\n');
                                        fis.log.error(err);
                                    })
                                    .on('end', function(){
                                        process.stdout.write('ok\n');
                                    });
                            }
                        });
                    } else {
                        fis.log.error('invalid framework name');
                    }
                    break;
                default :
                    commander.help();
            }
        });
    
    commander
        .command('start')
        .description('start server');
    
    commander
        .command('stop')
        .description('shutdown server');
    
    commander
        .command('restart')
        .description('restart server');
    
    commander
        .command('install <name>')
        .description('install server framework');
};
@@ -1495,32 +1495,67 @@
             %7D);%0A
+                fis.util.del(tmp);%0A
                 
@@ -1626,32 +1626,117 @@
             %7D);%0A
+        %7D else %7B%0A            if(callback)%7B%0A                callback();%0A            %7D%0A
         %7D%0A    %7D%0A

修复server.stop没有删除pid文件bug