var fs = require('fs')
var http = require("http")
var spawn = require('child_process').spawn

var log = function(message){
    console.log(message)
    //TODO write to a log file, add datetime and other info
}


/*
 * settings.json looks something like this: 
{
    "verboseResponses" : "true",
    "secretKey" : "sha1=somelonghashstringthatrepresentsyoursecretkey", 
    "repositories": [
        {   
            "name": "aarongreenwald/grouper", 
            "scriptDirectory": "sci/scripts/", 
            "script": "grouper.sh"
        },
        {   
            "name": "aarongreenwald/sci", 
            "scriptDirectory": "sci/scripts/", 
            "script": "sci.sh"
        }
    ],
    "port" : 31242
}
* 
* port will default to 31242 if ommitted
* verboseSettings will default to false if ommitted
 */

log('sci server starting...')

try {
    var settings = JSON.parse(fs.readFileSync('sci/settings.json', 'utf8'))
} 
catch (ex){
    log('Cannot parse settings file: ' + ex)
    throw ex
}

var repositories = settings.repositories
var port = settings.port || 31242


log('Listening for POST requests on port ' + port + '...')

http.createServer(function(request, response) {  
    
    var handleError = function(ex, response){
        response.writeHead(500, {"Content-Type": "text/plain"})
        if (settings.verboseResponses){
            response.write(ex.message || ex ||  'An uknown error occurred')    
        }
        else {        
            response.write('That didn\'t work. Try again.')        
        }    
        log(ex.message || ex || 'An unknown error occurred.') //TODO I should log more than this
    }

              
    var body = ' '                                
    request.on('data', function (data) {
        body += data                                                  
    })
    
    request.on('end', function () {
        try {                                     
            if (request.headers['user-agent'].indexOf('GitHub-Hookshot/') === -1){
                throw 'This request does not appear to originate from github. If you\'re going to try to break the system, at least try harder.'            
            }
                        
            if (request.headers['x-hub-signature'] !== settings.secretKey){
                throw 'You don\'t seem to be who you say you are. You need the key to enter!!'
            }
            
            if (request.method !== 'POST') {       
                throw 'Only POST requests are processed by this server.'         
            }
            
            if (request.headers['x-github-event'] !== 'push'){
                throw 'Only push events are processed by this server.'
            }
            
            try {           
                var payload = JSON.parse(body)                              
            } catch (ex) {                        
                throw   { 
                            message: 'Unable to parse payload: ' 
                                    + body 
                                    + '\n\nError: ' + ex
                        }
            }
            
            var found = false
            for (var i = 0; i < repositories.length; i++){
                var repository = repositories[i]
                if (payload.repository.full_name === repository.name){                    
                    spawn('sh', [ repository.script ], { 
                        cwd: repository.scriptDirectory
                    })                                      
                    found = true
                    break             
                } 
            }
            if (found){
                response.writeHead(200, {"Content-Type": "text/plain"})
                var message = 'Successfully processed continuous integration script for repository: ' + repository.name
                response.write(message) 
                log(message) //log more than this
            }
            else {                        
                throw 'Invalid repository name.'                        
            }                 
        } catch (ex) {                                        
            handleError(ex, response)                    
        }                     
        finally {                    
            response.end()
        }                                                          
    })                            
}).listen(port);

@@ -43,16 +43,45 @@
 %22http%22)%0A
+var https = require(%22https%22)%0A
 var spaw
@@ -115,16 +115,16 @@
 ).spawn%0A
-
 %0Avar log
@@ -386,24 +386,61 @@
 ecretkey%22, %0A
+%09%22ssl%22 : %22true%22,%0A%09%22sslOptions%22 : %7B%7D,%0A
     %22reposit
@@ -1146,87 +1146,30 @@
 42%0A%0A
-%0Alog('Listening for POST requests on port ' + port + '...')%0A%0Ahttp.createServer(
+var requestListener = 
 func
@@ -2256,16 +2256,54 @@
 nature'%5D
+ && request.headers%5B'x-hub-signature'%5D
  !== set
@@ -4452,26 +4452,214 @@
     
-                %0A%7D
+%0A%7D%0A%0Alog('Listening for POST requests on port ' + port + '...')%0A%0Aif (!settings.ssl)%7B%0A%09http.createServer(requestListener).listen(port)%0A%7D else %7B%09%0A%09https.createServer(settings.sslOptions %7C%7C %7B %7D, requestListener
 ).li
@@ -4668,10 +4668,11 @@
 en(port)
-;
+%0A%7D
 %0A

add support for ssl and make the secretKey optional