#! /usr/bin/env node
var fs      = require('fs');
var http    = require('http')
var request = require('request')

var config = JSON.parse(
    fs.readFileSync('config.json')
);

// Ensure all files in object
var mandatory_discourse_props = ["api_key", "api_user", "domain", "topic_id"]
var mandatory_webhook_props = ["secret"]

for (property of mandatory_discourse_props) {
    if (!config.discourse.hasOwnProperty(property)) {
        throw new Error("Required property discourse." + 
            property + 
            " not found in config.json")
    }
}

for (property of mandatory_webhook_props) {
    if (!config.webhook.hasOwnProperty(property)) {
        throw new Error("Required property webhook." + 
            property + 
            " not found in config.json")
    }
}

var handler = require('github-webhook-handler')({
    path: "/" + config.webhook.path,
    secret: config.webhook.secret
})

// Start the server with our handler
var port = config.webhook.hasOwnProperty('port') ? config.webhook.port : 8080
http.createServer(function (req, res) {
    handler(req, res, function (err) {
        res.statusCode = 404
        res.end('Not Found')
    })
}).listen(port, function() {
    console.log("Accepting webhooks to /" + config.webhook.path + " on port " 
                + port)
})

handler.on('push', function(event) {

    console.log("Received push from " + 
        event.payload["repository"]["full_name"])
    var commits = event.payload.commits

    // Handle multiple commits in one webhook
    for (var commit of commits) {

        // BUILD THE MESSAGE
        // We put together the forum post in Markdown
        // by splitting the commit message and adding
        // quote delimeters (`>`) to the beginning of
        // each. If it's the first line, add a `#` to
        // highlight it as a title. If your forum has
        // oneboxes and you'd rather use them, we can
        // skip this.

        var comment_text = ""
        if (config.hasOwnProperty('onebox_enabled') && config.onebox_enabled) {
            comment_text = commit.url
        } else {
            commit = commit.message.split("\n")
            comment_text = "_latest changes on github:_\n\n---\n"

            for (var x = 0; x < commit.length; x++) {
                var line = commit[x]
                comment_text += "> " + (x==0 ? "# " : "") + line + "\n"
            }

            comment_text += 
                "\n\n---\n_[more details at github](" +
                commit.url + 
                ") - this is an automated post_"
        }

        // MAKE THE COMMENT
        // Given the details you added to config.json
        // we make a POST to your thread with details
        // about your commit.

        var discourse_url = ((
            config.discourse.hasOwnProperty('https_enabled') && 
            config.discourse.https_enabled) 
            ? "https://" 
            : "http://"
        ) + config.discourse.domain

        request({
            url: discourse_url + "/posts",
            method: "POST",
            qs: {
                'api_key': config.discourse.api_key,
                'api_username': config.discourse.api_user
            },
            form: {
                topic_id: config.discourse.topic_id,
                raw: comment_text
            }
        }, function(err, res, body) {
            if (err) throw err
            var post_url = discourse_url + "/t/" + config.discourse.topic_id + 
                "/" + JSON.parse(body).post_number
            console.log("Success: " + commit.id + " / " + post_url)
        })
    };
})

handler.on('ping', function(event) {
    console.log("Received ping: " + event.payload.zen)
})

handler.on('error', function(event) {
    console.log(event)
})

@@ -1546,24 +1546,105 @@
 commits) %7B%0A%0A
+        console.log(%22Processing commit '%22 + commit.id + %22': %22 + commit.message)%0A%0A
         // B
@@ -2632,32 +2632,205 @@
 st_%22%0A        %7D%0A%0A
+        create_post(commit, comment_text)%0A%0A    %7D;%0A%7D)%0A%0Afunction create_post(commit, comment_text) %7B%0A%0A        // http://learndiscourse.org/discourse-api-documentation/#posts%0A%0A
         // MAKE 
@@ -3220,59 +3220,223 @@
     
-request(%7B%0A            url: discourse_url + %22/posts%22
+var post_url = discourse_url + %22/posts%22%0A%0A        console.log(%22Posting to Discourse: url=%22 + post_url + %22, topic_id=%22 + config.discourse.topic_id + %22, raw=%22 + comment_text)%0A        request(%7B%0A            url: post_url
 ,%0A  
@@ -3795,16 +3795,214 @@
 row err%0A
+            var response = JSON.parse(body)%0A            if (response.errors) %7B%0A                console.error(%22Error posting commit '%22 + commit.id + %22': %22 + response.errors)%0A            %7D else %7B%0A    
         
@@ -4089,16 +4089,20 @@
         
+  
+  
 %22/%22 + JS
@@ -4128,16 +4128,20 @@
 _number%0A
+    
         
@@ -4200,16 +4200,30 @@
 st_url)%0A
+            %7D%0A
         
@@ -4225,25 +4225,18 @@
      %7D)%0A
-    %7D;
 %0A%7D
-)
 %0A%0Ahandle

Add some log messages. Improve robustness and error handling.