#! /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.respository.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) {
            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_"
        } else {
            comment_text = commit.url
        }

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

        request({
            url: 
                (
                    (
                        config.discourse.hasOwnProperty('https_enabled') && 
                        config.discourse.https_enabled
                    ) 
                    ? "https://" 
                    : "http://"
                ) +
                config.discourse.domain +
                "/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
            console.log("Success: " + commit.id)
            console.log(res)
        })
    };
})

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

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

@@ -2716,79 +2716,31 @@
     
-request(%7B%0A            url: %0A                (%0A                    (%0A   
+var discourse_url = ((%0A
     
@@ -2743,33 +2743,24 @@
             
-         
 config.disco
@@ -2800,28 +2800,16 @@
 d') && %0A
-            
         
@@ -2846,38 +2846,11 @@
 bled
-%0A                    ) %0A      
+) %0A
     
@@ -2857,18 +2857,16 @@
         
-  
 ? %22https
@@ -2883,24 +2883,16 @@
         
-        
 : %22http:
@@ -2907,35 +2907,11 @@
     
-  
-      ) +%0A               
+) +
  con
@@ -2930,18 +2930,17 @@
 e.domain
- +
+%0A
 %0A       
@@ -2940,23 +2940,58 @@
         
-       
+request(%7B%0A            url: discourse_url +
  %22/posts
@@ -3371,72 +3371,188 @@
     
-console.log(%22Success: %22 + commit.id)%0A            console.log(res
+var post_url = discourse_url + %22/t/%22 + config.discourse.topic_id + %0A                %22/%22 + res.body%5B%22post_number%22%5D%0A            console.log(%22Success: %22 + commit.id + %22 / %22 + post_url
 )%0A  

Improve success logging