//
//   Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
//   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.
//

'use strict';

var path = require('path'),
    npid = require('npid'),
    conf = require('./conf');

// TBD: Check why log lib doesn't work here

module.exports = function configureProcess(serverName) {
    var processName = 'mas-' + serverName + '-' + conf.get('common:env');
    var pid;

    process.umask(18); // file: rw-r--r-- directory: rwxr-xr-x
    process.title = processName;

    if (conf.get('pid:enabled')) {
        var pidDirectory = conf.get('pid:directory');

        if (pidDirectory.charAt(0) !== path.sep) {
            pidDirectory = path.join(__dirname, '..', '..', pidDirectory);
        }

        var pidFile = path.join(pidDirectory, processName + '.pid');

        try {
            pid = npid.create(pidFile);
        } catch (e) {
            var msg = e.code === 'EEXIST' ? 'Pid file (' + pidFile + ') exists. ' +
                'Is the process already running?' : 'Unknown pid file error.';
            console.error(msg);
            process.exit(1);
        }

        pid.removeOnExit();

        var deletePidAndExit = function() {
            pid.remove();
            process.exit();
        };

        process.on('SIGINT', deletePidAndExit);
        process.on('SIGTERM', deletePidAndExit);
    }
};

@@ -725,54 +725,37 @@
 nf')
-;%0A%0A// TBD: Check why log lib doesn't work here
+,%0A    log = require('./log');
 %0A%0Amo
@@ -1345,16 +1345,48 @@
 dFile);%0A
+            pid.removeOnExit();%0A
         
@@ -1415,18 +1415,18 @@
     
-var msg = 
+log.error(
 e.co
@@ -1442,16 +1442,32 @@
 EXIST' ?
+%0A               
  'Pid fi
@@ -1499,29 +1499,8 @@
 ts. 
-' +%0A                '
 Is t
@@ -1529,16 +1529,32 @@
 ning?' :
+%0A               
  'Unknow
@@ -1565,119 +1565,30 @@
 d fi
-le error.';%0A            conso
 le
-.
+ 
 error
-(msg);%0A            process.exit(1);%0A        %7D%0A%0A        pid.removeOnExit();
+.');%0A        %7D
 %0A%0A  
@@ -1676,24 +1676,25 @@
 rocess.exit(
+0
 );%0A        %7D

Use log.error in init module