/**
 * agent.js
 * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * DongHee Yang <donghee.yang@samsung.com>
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jiil Hyoun <jiil.hyoun@samsung.com>
 * Jonghwan Park <iwin100.park@samsung.com>
 * Kitae Kim <kt920.kim@samsung.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 * - S-Core Co., Ltd
**/

var optimist = require('optimist');
var os = require('os');
var path = require('path');
var fs = require('fs');

var dibs = require('../../../core/dibs.js');

// option parse & set
var argv = optimist.usage(
    'Usage: agent-svr SUBCOMMAND [OPTS] or $0 (-h)' + os.EOL +
    'Subcommands:' + os.EOL +
    '    start           Start agent-server.' + os.EOL +
    '    stop            Stop agent-server.' + os.EOL +
    os.EOL +
    'Subcommand usage:' + os.EOL +
    '    agent-svr start -i <server id> -p <port>' + os.EOL +
    '    agent-svr stop -i <server id>' + os.EOL
).alias({
    i: 'id',
    p: 'port',
    h: 'help'
})
    .string(['i'])
    .describe('i', 'agent server id')
    .describe('p', 'port')
    .describe('h', 'display help')
    .default('p', 38971)
    .demand('i')
    .argv;

var subCmds = argv._;

if (argv.h) {
    optimist.showHelp();
    process.exit(0);
}

if (!subCmds || subCmds.length === 0) {
    console.error('Sub-Command must be specified!');
    process.exit(-1);
}

// init variable
var serverId = argv.i;
var serverPort = parseInt(argv.p, 10);
var server = null;

switch (subCmds[0]) {
case 'start':
    handle_start_command(serverId, serverPort);
    break;
case 'stop':
    handle_stop_command(serverId);
    break;
default:
    console.error('Invalid sub-command!: \'' + subCmds[0] + '\'');
    process.exit(-1);
}


function handle_start_command(serverId, serverPort) {

    // check arguments
    if (!serverId || serverId.length === 0) {
        console.error('Server ID MUST be specified!');
        process.exit(-1);
    }
    if (isNaN(serverPort)) {
        console.error('Port option(-p) MUST be specified!');
        process.exit(-1);
    }

    dibs.initialize();
    try {
        server = dibs.createServer(serverId, 'agent');
    } catch (err) {
        console.log(err.message);
        process.exit(-1);
    }

    // start server
    server.start(serverPort, {}, function (err) {
        if (err) {
            if (err.message) {
                console.error(err.message);
            } else {
                console.error(err);
            }
            process.exit(-1);
        }
    });
}


function handle_stop_command(serverId) {

    // check arguments
    if (!serverId || serverId.length === 0) {
        console.error('Server ID MUST be specified!');
        process.exit(-1);
    }

    // create server
    dibs.initialize();
    server = loadAgentServer(serverId);
    dibs.addServer(server);

    server.terminateServer(function (err) {
        if (err !== null) {
            console.log('server stop failed');
            console.log(err);
        }
    });
}


function loadAgentServer(serverId) {
    dibs.initialize();

    // find server
    var dibsConfigDir = dibs.config.getConfigDir();
    var workingPortFile = path.join(dibsConfigDir, serverId, 'PORT');
    if (!fs.existsSync(workingPortFile)) {
        console.error('Server is not working!');
        process.exit(-1);
    }

    var svr = dibs.createServer(serverId, 'agent');
    svr.host = '127.0.0.1';
    svr.port = parseInt(fs.readFileSync(workingPortFile), 10);
    return svr;
}
