#!/usr/bin/env nodejs

'use strict';

/**
 * Module dependencies.
 */

var http = require('http'),
    express = require('express'),
    serve_static = require('serve-static'),
    serve_index = require('serve-index'),
    errorhandler = require('errorhandler'),
    routes = require('./routes'),
    config = require('./lib/config.js'),
    utils = require('./lib/utils.js'),
    Client = require('./lib/client.js'),
    Broadcaster = require('./lib/broadcaster.js');

var app = module.exports = express(),
    server = http.createServer(app),
    io = require('socket.io')(server),
    env = process.env.NODE_ENV || 'development';

if ('development' == env) {
    app.use(errorhandler({
        dumpExceptions: true,
        showStack: true
    }));
} else if ('production' == env) {
    app.use(errorhandler());
}

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// Routes
app.get('/', routes.index);
// distibution page
app.get(config.routes.distribution, routes.distribution);
// parefernces page
if (config.routes.preferences)
    app.get(config.routes.preferences, routes.preferences);
// commands page
if (config.routes.commands)
    app.get(config.routes.commands, routes.commands);
// debomatic static page
app.use(config.routes.debomatic, serve_index(config.debomatic.path));
app.use(config.routes.debomatic, serve_static(config.debomatic.path));
// serve stylesheet-javascript
app.use(serve_static(__dirname + '/public'));

// serve dsc files as octet-stream
serve_static.mime.define({
    'application/octet-stream': ['dsc']
});

// Listening
server.listen(config.port, config.host, null, function (err) {

    // Checking nodejs with sudo:
    // Find out which user used sudo through the environment variable
    // and set his user id
    var uid = parseInt(process.env.SUDO_UID);
    if (uid) {
        console.log('Please do not run nodejs with sudo. Changing user to %d', uid);
        process.setgid(uid);
        process.setuid(uid);
    }

    // statuses
    var status = [];

    var broadcast = new Broadcaster(io.sockets, status);

    io.sockets.on('connection', function (socket) {
        var client = new Client(socket);
        client.start();
        if (status.length > 0)
            client.send_status(status);
        client.send_status_debomatic();
    });

    console.log('Debomatic-webui listening on %s:%d in %s mode', server.address().address, server.address().port, app.settings.env);
});

server.on('error', function (e) {
    if (e.code == 'EADDRINUSE') {
        console.log('Address in use %s:%d. Exit.', config.host, config.port);
        process.exit(1);
    } else {
        console.error(e);
    }
});
